note 91047 modified in function.number-format by danbrown

From: Date: Mon, 25 May 2009 22:22:10 +0000
Subject: note 91047 modified in function.number-format by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156002@lists.php.net to get a copy of this message
In my function my_number_format() [shown below] there was a bug. If a negative number which is smaller than 1 was entered (-0,...), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value). Here is the corrected version: <?php function my_number_format($number, $dec_point, $thousands_sep) { $was_neg = $number < 0; // Because +0 == -0 $number = abs($number); $tmp = explode('.', $number); $out = number_format($tmp[0], 0, $dec_point, $thousands_sep); if (isset($tmp[1])) $out .= $dec_point.$tmp[1]; if ($was_neg) $out = "-$out"; return $out; } ?> Thanks to Federico Cassinelli for the bug report. [EDIT BY danbrown AT php DOT net: The original note follows.] Let's say we got the number $inp = 1234.56 By using <?php return number_format($inp, 2, ',', '.'); ?> you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator) But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits! But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function. But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456 So, I created following function, that doesn't change the amount of fractional digits: <?php function my_number_format($number, $dec_point, $thousands_sep) { $tmp = explode('.', $number); $out = number_format($tmp[0], 0, $dec_point, $thousands_sep); if (isset($tmp[1])) $out .= $dec_point.$tmp[1]; return $out; } ?> --was-- In my function my_number_format() ( post http://www.php.net/manual/en/function.number-format.php#84420 ) there was a bug. If a negative number which is smaller than 1 was entered (-0,...), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value). Here is the corrected version: <?php function my_number_format($number, $dec_point, $thousands_sep) { $was_neg = $number < 0; // Because +0 == -0 $number = abs($number); $tmp = explode('.', $number); $out = number_format($tmp[0], 0, $dec_point, $thousands_sep); if (isset($tmp[1])) $out .= $dec_point.$tmp[1]; if ($was_neg) $out = "-$out"; return $out; } ?> Thanks to Federico Cassinelli for the bug report. http://php.net/manual/en/function.number-format.php

« previous php.notes (#156002) next »