Arithmetic

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Deelight
Forum Newbie
Posts: 10
Joined: Mon Jul 04, 2005 6:50 pm

Arithmetic

Post 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 :)
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

number_format or if you come from a C background, there's the normal family of printf's.
theda
Forum Contributor
Posts: 332
Joined: Sat Feb 19, 2005 8:35 am
Location: USA

Post 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
?>
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

It helps to understand what's going behind the seens.

Code: Select all

$var1 = 5.00
$var1 is now a float with the value of 5.

Code: Select all

$var2 = 5.50
$var2 is now a float with the value of 5.5 (see, they don't care about the trailing zero)

Code: Select all

$var3 = $var1 + $var2;
PHP has just done an operation on the two variables, adding two floats, and gets 10.5

Code: Select all

print $var3
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.
Deelight
Forum Newbie
Posts: 10
Joined: Mon Jul 04, 2005 6:50 pm

Post by Deelight »

Thanks for the great indepth explanation guys, this has been helpfull :)
Post Reply