HOME IRC
gelignite
Promotion
Nutzloses Wissen
Deine IP:
3.17.154.171

Dein Host:
ec2-3-17-154-171.us-east-2.compute.amazonaws.com

Seitenaufbau dauerte:


Aktuelle Uhrzeit (UTC):
19-04-2024 22:54:59

Letzten Lottozahlen [?]:
9, 16, 34, 37, 40, 47
SZ: 2
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