php intval() and floor() return value that is too low?

淺唱寂寞╮ 提交于 2019-12-18 04:39:06

问题


Because the float data type in PHP is inaccurate, and a FLOAT in MySQL takes up more space than an INT (and is inaccurate), I always store prices as INTs, multipling by 100 before storing to ensure we have exactly 2 decimal places of precision. However I believe PHP is misbehaving. Example code:

echo "<pre>";

$price = "1.15";
echo "Price = ";
var_dump($price);

$price_corrected = $price*100;
echo "Corrected price = ";
var_dump($price_corrected);


$price_int = intval(floor($price_corrected));
echo "Integer price = ";
var_dump($price_int);

echo "</pre>";

Produced output:

Price = string(4) "1.15"
Corrected price = float(115)
Integer price = int(114)

I was surprised. When the final result was lower than expected by 1, I was expecting the output of my test to look more like:

Price = string(4) "1.15"
Corrected price = float(114.999999999)
Integer price = int(114)

which would demonstrate the inaccuracy of the float type. But why is floor(115) returning 114??


回答1:


Try this as a quick fix:

$price_int = intval(floor($price_corrected + 0.5));

The problem you are experiencing is not PHP's fault, all programming languages using real numbers with floating point arithmetics have similar issues.

The general rule of thumb for monetary calculations is to never use floats (neither in the database nor in your script). You can avoid all kinds of problems by always storing the cents instead of dollars. The cents are integers, and you can freely add them together, and multiply by other integers. Whenever you display the number, make sure you insert a dot in front of the last two digits.

The reason why you are getting 114 instead of 115 is that floor rounds down, towards the nearest integer, thus floor(114.999999999) becomes 114. The more interesting question is why 1.15 * 100 is 114.999999999 instead of 115. The reason for that is that 1.15 is not exactly 115/100, but it is a very little less, so if you multiply by 100, you get a number a tiny bit smaller than 115.

Here is a more detailed explanation what echo 1.15 * 100; does:

  • It parses 1.15 to a binary floating point number. This involves rounding, it happens to round down a little bit to get the binary floating point number nearest to 1.15. The reason why you cannot get an exact number (without rounding error) is that 1.15 has infinite number of numerals in base 2.
  • It parses 100 to a binary floating point number. This involves rounding, but since 100 is a small integer, the rounding error is zero.
  • It computes the product of the previous two numbers. This also involves a little rounding, to find the nearest binary floating point number. The rounding error happens to be zero in this operation.
  • It converts the binary floating point number to a base 10 decimal number with a dot, and prints this representation. This also involves a little rounding.

The reason why PHP prints the surprising Corrected price = float(115) (instead of 114.999...) is that var_dump doesn't print the exact number (!), but it prints the number rounded to n - 2 (or n - 1) digits, where n digits is the precision of the calculation. You can easily verify this:

echo 1.15 * 100;  # this prints 115
printf("%.30f", 1.15 * 100);  # you 114.999....
echo 1.15 * 100 == 115.0 ? "same" : "different";  # this prints `different'
echo 1.15 * 100 < 115.0 ? "less" : "not-less";    # this prints `less'

If you are printing floats, remember: you don't always see all digits when you print the float.

See also the big warning near the beginning of the PHP float docs.




回答2:


The other answers have covered the cause and a good workaround to the problem, I believe.

To aim at fixing the problem from a different angle:

For storing price values in MySQL, you should probably look at the DECIMAL type, which lets you store exact values with decimal places.




回答3:


PHP is doing rounding based on significant digits. It's hiding the inaccuracy (on line 2). Of course, when floor comes along, it doesn't know any better and lops it all the way down.




回答4:


Maybe it's another possible solution for this "problem":

intval(number_format($problematic_float, 0, '', ''));



回答5:


As stated this is not a problem with PHP per se, It is more of an issue of handling fractions that can't be expressed as finite floating point values hence leading to loss of character when rounding up.

The solution is to ensure that when you are working on floating point values and you need to maintain accuracy - use the gmp functions or the BC maths functions - bcpow, bcmul et al. and the problem will be resolved easily.

E.g instead of $price_corrected = $price*100;

use $price_corrected = bcmul($price,100);



来源:https://stackoverflow.com/questions/812815/php-intval-and-floor-return-value-that-is-too-low

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!