Page 1 of 1
Arithmetic
Posted: Tue Jul 19, 2005 10:21 am
by Deelight
Hello people
I have a little issue with PHP cutting off my decimals.
Code: Select all
<?php
$var1 = 5.00;
$var2 = 5.50;
print $var1 + $var2;
?>
This will print 10.5 but I want it to print 10.50
How do I make sure I always have 2 decimals behind the point?
Thanks

Posted: Tue Jul 19, 2005 10:37 am
by nielsene
number_format or if you come from a C background, there's the normal family of printf's.
Posted: Tue Jul 19, 2005 1:30 pm
by theda
Example:
Code: Select all
<?
$num1 = 5.555;
$num2 = 5.0;
$number = $num1 + num2; // Adds up to 10.555
echo number_format($number, 2, '.', ','); // Rounds to 10.55
?>
Posted: Tue Jul 19, 2005 2:48 pm
by Ambush Commander
It helps to understand what's going behind the seens.
$var1 is now a float with the value of 5.
$var2 is now a float with the value of 5.5 (see, they don't care about the trailing zero)
PHP has just done an operation on the two variables, adding two floats, and gets 10.5
Now, here's the jiffy part. You can't "print" persay a floating point number: the only thing you can print are strings. PHP, however, does this conversion automatically for you. But it turns out,
(float) 10.5 == (string) '10.5' not '10.50'
So, what the other people have suggested basically overrides PHP's internal conversion from float to string and instead, let's you decide how the string comes out. PHP is not cutting off your decimals: it never acknowledged them in the first place.
Posted: Wed Jul 20, 2005 3:07 am
by Deelight
Thanks for the great indepth explanation guys, this has been helpfull
