As we all know, floating point arithmetic is not always completely accurate, but how do you deal with its inconsistencies?
As an example, in PHP 5.2.9: (this doesn't happen in 5.3)
echo round(14.99225, 4); // 14.9923
echo round(15.99225, 4); // 15.9923
echo round(16.99225, 4); // 16.9922 ??
echo round(17.99225, 4); // 17.9922 ??
echo round(25.99225, 4); // 25.9922 ??
echo round(26.99225, 4); // 26.9923
How would you work around this?
php $num = 67; $number = sprintf('%. 2f', $num); echo "The number upto two decimal places is $number"; ?> Here, we have used %f for a float value.
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.
The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.
Welcome to IEEE754, enjoy your stay.
Use bc
or gmp
instead.
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