I have this number:
$double = '21.188624';
After using number_format($double, 2, ',', ' ')
I get:
21,19
But what I want is:
21,18
Any ideea how can I make this work?
Thank you.
Rules for Rounding Here's the general rule for rounding: If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.
$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Show activity on this post. This will give you 2 number after decimal.
Parameter Values Specifies a constant to specify the rounding mode: PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2.
number_format
will always do that, your only solution is to feed it something different:
$number = intval(($number*100))/100;
Or:
$number = floor(($number*100))/100;
I know that this an old question, but it still actual :) .
How about this function?
function numberFormatPrecision($number, $precision = 2, $separator = '.') { $numberParts = explode($separator, $number); $response = $numberParts[0]; if (count($numberParts)>1 && $precision > 0) { $response .= $separator; $response .= substr($numberParts[1], 0, $precision); } return $response; }
Usage:
// numbers test numberFormatPrecision(19, 2, '.'); // expected 19 return 19 numberFormatPrecision(19.1, 2, '.'); //expected 19.1 return 19.1 numberFormatPrecision(19.123456, 2, '.'); //expected 19.12 return 19.12 numberFormatPrecision(19.123456, 0, '.'); //expected 19 return 19 // negative numbers test numberFormatPrecision(-19, 2, '.'); // expected -19 return -19 numberFormatPrecision(-19.1, 2, '.'); //expected -19.1 return -19.1 numberFormatPrecision(-19.123456, 2, '.'); //expected -19.12 return -19.12 numberFormatPrecision(-19.123456, 0, '.'); //expected -19 return -19 // precision test numberFormatPrecision(-19.123456, 4, '.'); //expected -19.1234 return -19.1234 // separator test numberFormatPrecision('-19,123456', 3, ','); //expected -19,123 return -19,123 -- comma separator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With