Re: Floored!

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ben Miller wrote:
If anyone has an answer for this, I would be greatly appreciative.

I was trying to compare two values, the first is the total cost of products
to be refunded, and the second is the original order total.  To the naked
eye, they both were coming out as 102.85, yet an if($Refund_Amount >
$Order_Total) was coming back true, so.....

I ran some tests, and did the following:

		$Order_Total = sprintf("%01.20f",$Order_Total);
		$Refund_Amount = sprintf("%01.20f",$Refund_Amount);

which produced:

		$Order_Total = 102.84999999999999431566
and		$Refund_Amount = 102.85000000000000852651

so, I figured I would try the following to make sure that the figures in the
database weren't weird:

		$Bar = 102.85;
		$Foo = sprintf("%01.20f",$Bar);

		echo "\$Foo = $Foo";

which produced:

		$Foo = 102.84999999999999431566;

I am completely lost.

Read the note on floating point precision here:

  http://us3.php.net/manual/en/language.types.float.php

You need to either work completely in pennies and only convert to dollars for display purposes so you are always working with integers, or you need to introduce a little fuzz factor whenever you are doing operations on floating point values.

There is simply no way for a computer to accurately represent a fraction with anything other than an estimation. The typical fix if you don't want to switch to using integer math is to add an appropriate fuzz factor. Like this:

  $fuzz = 0.0000001;
  if(floor($value+$fuzz) == 10) ...

That is, if the floating point $value happens to be 9.99999999999 or 10.00000000001 then applying this fuzz factor and doing the floor operation, you will always get 10 as long as your fuzz factor is larger than the precision error of your machine.

-Rasmus

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux