HOME IRC
gelignite
Promotion
Nutzloses Wissen
Deine IP:
3.238.90.95

Dein Host:
ec2-3-238-90-95.compute-1.amazonaws.com

Seitenaufbau dauerte:


Aktuelle Uhrzeit (UTC):
05-10-2022 18:09:21

Letzten Lottozahlen [?]:
1, 3, 19, 37, 43, 49
SZ: 0
Tipps und Tricks
zurück

Code Snippet - Real truncation function (PHP)


Direct link:
Tips und Tricks #7
Bezug:
PHP (Zend)

Details:
Sometimes you need to truncate a number (float or double) to a specified count of decimals. But whatever function you use e.g. (s)printf, number_format, round (floor, ceil) it just does not truncate your number but rounds it for God's sake.

To output a simply truncated but not rounded number you want the following truncate function. It uses some simple math. It adds a small offset to your number and then uses the rounding fetish of sprintf to fit your needs. Here we go:
<?php
/**
 * sprintf() does normal rounding.
 * To achieve a truncation an appropriate offset has to be applied beforehand.
 */
function truncate$number$decimals )
{
  
$offset '0.'str_repeat0$decimals ).'5';
  return 
sprintf"%.{$decimals}f"$number $offset ); // Reduce $number by $offset and round
                                                         // appropriate by sprintf()
}

$number 2.7172;

echo 
truncate$number)."\r\n"// 2.7
echo truncate$number)."\r\n"// 2.71
echo truncate$number)."\r\n"// 2.717

/**
 * No problem either, if you need to number_format()
 */
$number 112233445.566778899;

echo 
number_formattruncate$number), 1',''.' )."\r\n"// 112.233.445,5
echo number_formattruncate$number), 2',''.' )."\r\n"// 112.233.445,56
echo number_formattruncate$number), 3',''.' )."\r\n"// 112.233.445,566
?>
Letzte Meldungen
13.08.2011 - Counter-Strike GO ...[more]

10.04.2011 - Monday Night Combat ...[more]

25.02.2011 - Humorvolles ...[more]

23.01.2011 - 1.5 GHz, 3 GB Speicher, ... ...[more]

20.01.2011 - Liste der QuakeNet Achievements und wie man sie bekommt bereitgestellt ...[more]

31.12.2010 - Guten Rutsch ...[more]

16.12.2010 - gelignAIte - Official Release ...[more]

11.11.2010 - openTTD AI ...[more]

26.10.2010 - Zeitreisen scheinen möglich ...[more]

04.09.2010 - Abschaltung "index.php4" ...[more]

Umfrage
Lieber ATI oder NVidia?

Legal notes
© 2000 - 2021 The Black Eagle Eyes, Alle Rechte vorbehalten