Floating Point Arithetic - Cant Add Up

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
gregambrose
Forum Newbie
Posts: 12
Joined: Thu Aug 07, 2003 11:01 pm
Location: Sydney, Australia

Floating Point Arithetic - Cant Add Up

Post by gregambrose »

I know floating point numbers can be a bit tricky but something as simple as the following should work correctly shouldn't it? It would in Java (OK I haven't tried it it but when I was working in Java I'm sure I had no such problem).

Code: Select all

<?php

	$a 	= 86.85;
	$b 	= 347.71;
	$c	= 260.86;
	
	$tot = $a + $c;
	
	$diff = $tot - $b;
	
	print($diff);
?>
Why don't we get zero as an answer? I've tried it on 4.3 php on Windows and 4.4.0 php on linux
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

viewtopic.php?t=37751 has some explanation
gregambrose
Forum Newbie
Posts: 12
Joined: Thu Aug 07, 2003 11:01 pm
Location: Sydney, Australia

Post by gregambrose »

Thanks for the reply. I guess I need to move to integers for money (as cents) to avoid the issue altogether. There seems no elegant solution, so the only way is to use round() every time you do anything with floats.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you could use arbitrary precision math functions: http://php.net/bcmath
gregambrose
Forum Newbie
Posts: 12
Joined: Thu Aug 07, 2003 11:01 pm
Location: Sydney, Australia

Post by gregambrose »

Thanks yes I could, but I think for money I would be more sure of integers. For other people bcmath might be a good alternative, though one would need to check that it doesn't suffer from similar problems to floats.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it doesn't suffer from any such problems. It uses strings to store the results. The range a number can be for it is abitrary compared to the finite range of an integer or floating point. For financial calculations, it is the better choice.
gregambrose
Forum Newbie
Posts: 12
Joined: Thu Aug 07, 2003 11:01 pm
Location: Sydney, Australia

Post by gregambrose »

If you think it is a good idea I'll give it a go. Thanks again for all your help.
Post Reply