The sprinf behaviour below is very strange.
// The code below outputs 1639
$value = floatval('16.40') * 100;
echo sprintf('%d', $value);
But when I use %f it outputs 1640.000000
I dumped the $value, it's definitely float(1640).
Does anyone knows what happened when I use %d? Is this a PHP bug? I've tested in PHP7.
The variable $value contains a floating point number. Floating point numbers are not exact, they are approximations.1
The value of $value is not 1640 but 1639.99999999999977262632. When you use %f to print it, printf() rounds it to 6 decimal places and the rounded value is 1640.000000.
When it is printed with %d, printf() uses only the integer part of $value and it is 1639.
Use round() to get the correct integer value:
printf('%d', round($value, 0));
Or, even better, use number_format() to get the value as string:
echo(number_format($value, 0, '', ''));
Both print 1640.
1 Think of 1/3. It is approximatively 0.3333333333 but one cannot represent it exactly because it has an infinite number of 3 after the decimal dot. In mathematics, 3 * 1/3 = 1 but in real life (and in computers), 3 * 0.333333333 is never 1, no matter how many 3 we put after the decimal dot. The computer programs usually round the value to some number of decimal places and it ends up being displayed as 1 but this doesn't happen always.
When it doesn't happen, another question similar to this one pops up on StackOverflow.
Related
floor function in PHP behave weirdly.
For 16 decimal values it gives floor value but by increasing 1 decimal it round.
$int = 0.99999999999999999;
echo floor($int); // returns 1
$int = 0.9999999999999999;
echo floor($int); // returns 0
$int = 0.99999999999999994;
echo floor($int); // returns 0
Is it defined/explained somewhere, at which point it gives "round" value?
Is there any function which gives 0 anyhow how many 9 in decimals?
It's not floor that rounds, it's floating point math that does.
This line:
echo 0.99999999999999999;
Prints 1 (demo) because 0.99999999999999999 is too precise to be represented by a (64-bit?) float, so the closest possible value is taken, which happens to be 1.
0.99999999999999994 is also too precise to be represented exactly, but here the closest representable value happens to be 0.9999999999999999.
Is it defined/explained somewhere, at which point it gives "round" value?
It's complicated, but the numbers are rounded almost always.
I believe there is no definition of "from when values will be approximated", but that is a mathematical property that follows from the definitions in the IEEE 754 floating point standard.
To be safe, just assume everything is approximated.
Is there any function which gives 0 anyhow how many 9 in decimals?
No. The problem is that, for PHP, 0.99999999999999999 is literally the same as 1.
They're represented by exactly the same sequence of bits, so it can't distinguish them.
There are some solutions to work with bigger precision decimals, but that requires some major code changes.
Probably of interest to you:
Working with large numbers in PHP
Note that while you may get arbitrary precision, you will never get infinite precision, as that would require infinite amounts of storage.
Also note that if you actually were dealing with infinite precision, 0.999... (going on forever) would be truly (as in, mathematically provable) equal to 1, as explained in depth in this Wikipedia article.
$float_14_digits = 0.99999999999999;
echo $float_14_digits; // prints 0.99999999999999
echo floor($float_14_digits); // prints 0
$float_15_digits = 0.999999999999999;
echo $float_15_digits; // prints 1
echo floor($float_15_digits); // prints 1
exit;
on my development machine that behavior happens on digit '15' not '17' like yours. PHP rounds the last digit in the floating numbers. your floor() function has nothing to do with this behavior
I have a question regarding number formating in PHP.
I have a variable called "average", which is simply an average of a few values. To make it clear I rounded the number to 2 decimal places. Now the problem is, that if the average is for example 2.90, it only shows 2.9. Is there any way of displaying 2 decimal places always? I though I could do it by multiplying the number by 100, rounding it to zero d.p. and then divide by 100 again, but that seems a bit overcomplicated if there is an easier way of doing it.
Maybe you can try the number_format(float $number [, int $decimals = 0 ])?
For more information, take a look at http://php.net/manual/en/function.number-format.php
Format the output with printf
printf("%.1f", $num); // prints 1 decimal place
printf("%.2f", $num); // prints 2 decimal places
I'm working with currency input. Only two digits after decimal mark should be used. I tried casting input to float and multiplying by 100, which works fine until someone enters more than two digits after decimal mark:
// Returns 6999.8 instead of 6999
$cents = floatval('69.998') * 100;
Then I tried casting result to int, so sequential digits after decimal point are ignored. It solves above problem ('69.998' becomes 6999), but creates a new one with float to integer conversion:
// Returns 6998 instead of 6999
$cents = intval(floatval('69.99') * 100);
I also considered floor(), but it triggers the same float issue as intval().
This is what I'm thinking about using:
$cents = intval((string)(floatval('69.99') * 100));
It works in both cases, but feels like a hack and it's late and my head hurts so maybe I'm missing something obvious here. Is there a better way to do this?
Is
$cents = intval(round(floatval('69.99') * 100));
what you need?
You can also specify the precision. For example, in your case you mentioned you would like to round the original to two decimal places:
$twodecimal = round(floatval('69.998'),2);//returns a float representation of 70
Be sure to have a look at the big red notice in these docs
It's because 69.99 * 100 has a floating-point representation of 6998.9999999* (off: you can check it at a javascript console too). If you want to be precise, you should use a fixed-point number with a php-extension, like BCMath - or, you can write a simple regexp for this specific problem
$amount = '69.99';
if (preg_match('/^(-?\d+)(\.(\d{1,2}))?/', $amount, $matches))
{
$amount = (int) ($matches[1] . (isset($matches[3]) ? str_pad($matches[3], 2, '0') : '00'));
}
else
{
$amount = ((int) $amount) * 100;
}
$cents = intval(round(floatval('69.99') * 100));
This would get it to the nearest number correctly, this is because of floating pointer precision problems as 69.99 is probably represented in memory to be something like 69.9899999
intval just truncates the remaining parts of the decimal, so 69.989999 * 100 becomes 6998.9999 and gets truncated to 6998
I would recommend that you use an integer to contain a currency value. Using floats can rapidly lead to rounding errors.
In the applications that I have seen, an integer is used with an assumed decimal point. All values are held to the nearest unit of currency such as the cent for US dollars or the Euro. There are currencies which do not have a decimal point and there are a couple that rather than two decimal places have three decimal places.
By manipulating with integers with an assumed decimal place, you can really reduce rounding errors and other issues that can be seen with floating point.
To do conversion, I recommend using string manipulation and removing the decimal point with string manipulation as well as performing a check to ensure that only the desired number of places are entered.
How come the result for
intval("19.90"*100)
is
1989
and not 1990 as one would expect (PHP 5.2.14)?
That's because 19.90 is not exactly representable in base 2 and the closest approximation is slightly lower than 19.90.
Namely, this closest approximation is exactly 2^-48 × 0x13E66666666666. You can see its exact value in decimal form here, if you're interested.
This rounding error is propagated when you multiply by 100. intval will force a cast of the float to an integer, and such casts always rounds towards 0, which is why you see 1989. Use round instead.
You can also use bc* function for working with float :
$var = bcmul("19.90", "100");
echo intval($var);
intval converts doubles to integers by truncating the fractional component of the number. When dealing with some values, this can give odd results. Consider the following:
print intval ((0.1 + 0.7) * 10);
This will most likely print out 7, instead of the expected value of 8.
For more information, see the section on floating point numbers in the PHP manual
Why are you using intval on a floating point number? I agree with you that the output is a little off but it has to do with the relative inprecision of floating point numbers.
Why not just use floatval("19.90"*100) which outputs 1990
I believe the php doc at http://de2.php.net/manual/en/function.intval.php is omitting the fact that intval will not deliver "the integer value" but the integer (that is non-fractional) part of the number. It does not round.
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??
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.
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.
Maybe it's another possible solution for this "problem":
intval(number_format($problematic_float, 0, '', ''));
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.
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);