PHP: Limits when Counting with float values - php

I need to count numbers but have to use a float datatype (don't as why - it's kind of an embedded system).
The simple counter goes like:
$num=1.0;
do {
$num = $num + 1;
// do some stuff
// ...
} while (...);
Question 1: What is the biggest number that can be counted correctly using a 32-bit and a 64-bit PHP system?
Question 2: When $num is read from a MySQL database using a standard FLOAT type (no precision specified) at the beginning of the loop and stored back at the end of the loop, is the answer to Question 1 still valid?

PHP uses double precision floating point, which has a 52-bit mantissa. This means that integers represented using floats start losing precision when they reach 253 (the extra bit of precision is because the leading bit of a normalized mantissa is always 1, so this doesn't need to be included explicitly in the representation). The following example demonstrates this:
echo number_format(pow(2.0, 53)-1) . "<br>" .
number_format(pow(2.0, 53)) . "<br>" .
number_format(pow(2.0, 53)+1);
outputs:
9,007,199,254,740,991
9,007,199,254,740,992
9,007,199,254,740,992
To get equivalent floating point precision in MySQL you should use the DOUBLE datatype, which is 64-bit floating point. If you just use FLOAT you'll get 32-bit single precision, which only has 23 bits of mantissa, and loses integer precision at 16,777,216.
See FLOAT and DOUBLE Data Type Representation for more details about how MySQL stores floating point internally.

Related

Additional digits after decimal points

Select Query giving additional digits after decimal point.
The datatype of the column is decimal(4,2).
The value stored is 1.39 but what i get is 1.3899999999999999.
I can perform round,number_format in php but Is there a way to get the exact value without extra digits after decimal ??
Database is MSSQL.
Most probably your database library is converting the DECIMAL(4, 2) datatype to a float behind the scenes. Now 1.39 cannot be expressed exactly as a floating point number, instead it is approximated to 1.3899999999999999023003738329862244427204132080078125 (use an online converter or do a <?php ini_set("precision", 99); var_dump(1.39);).
There are some workarounds, the simplest one is to convert the decimal number to string at the query level:
SELECT CAST(col AS VARCHAR(4)) AS col_as_string FROM ...
The other solution is to use the number_format function which seems to round the values.
Be aware the PHP has no precise data type for numbers with decimal places. When working with such numbers it will always use an approximite data type (floating point numbers).
So comparing 0.1 + 0.2 with 0.3 for instance may very likely result in false. That means: be careful with equality comparisions.
When displaying such values you should never rely on the default presentation, but use number_format instead. E.g. number_format($value, 2).
If you want to avoid floating point issues completely, then don't use numbers with decimal places. That can be a hassle though (e.g. retrieving the integer 139 for 1.39 and keeping in mind that this value means hundredths).
I suspect 1.39 can't be exactly represented as a float.
I don't know PHP, so here is some Java code to demonstrate:
class DoubleFloat {
public static void main(String[] args) {
float f = 1.39f;
double d = 1.39f;
System.out.println("f = " + f);
System.out.println("d = " + d);
}
}
The output:
f = 1.39
d = 1.3899999856948853
Depends what you are trying to do on the PHP side, but you could store the number as an integer, e.g. 1.39 is stored as 139 and convert it somehow on the PHP side.

Error with floating and rounding down? [duplicate]

Can anyone explain the below output in PHP?
$num1 = (1.65 - 1.00);
echo "<br><br>num1 = " . $num1; // Output: int = 0.65
$num_int1 = $num1 * 100;
echo "<br><br>int = " . $num_int1; // Output: int = 65
$num_int2 = (int) $num_int1;
echo "<br><br>int = " . $num_int2; // Output: int = 64
Why $num_int2 is 64?
Thanks for help.
From an article I wrote for Authorize.Net (in your specific case $num_int1 is a float even if it looks like an integer):
One plus one equals two, right? How about .2 plus 1.4 times 10? That equals 16, right? Not if you're doing the math with PHP (or most other programming languages):
echo floor((0.2 + 1.4) * 10); // Should be 16. But it's 15!
This is due to how floating point numbers are handled internally. They are represented with a fixed number of decimal places and can result in numbers that do not add up quite like you expect. Internally our .2 plus 1.4 times 10 example computes to roughly 15.9999999998 or so. This kind of math is fine when working with numbers that do not have to be precise like percentages. But when working with money precision matters as a penny or a dollar missing here or there adds up quickly and no one likes being on the short end of any missing money.
The BC Math Solution
Fortunately PHP offers the BC Math extension which is "for arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings." In other words, you can do precise math with monetary values using this extension. The BC Math extension contains functions that allow you to perform the most common operations with precision including addition, subtraction, multiplication, and division.
A Better Example
Here's the same example as above but using the bcadd() function to do the math for us. It takes three parameters. The first two are the values we wish to add and the third is the number of decimal places we wish to be precise to. Since we're working with money we'll set the precision to be two decimal palces.
echo floor(bcadd('0.2', '1.4', 2) * 10); // It's 16 like we would expect it to be.

Why does PHP transform 15+ digit long integer on output [duplicate]

This question already has answers here:
round in PHP shows scientific notation instead of full number
(3 answers)
Closed 9 years ago.
Why does echo 100000000000000; output 1.0E+14 and not 100000000000000?
This kind of transformation of integers on output happens only for integers that are 15 digits long and longer.
PHP will convert an integer to float if it is bigger than PHP_INT_MAX. For 32-bit systems this is 2147483647.
The answer to the questions is related to the string representation of floats in PHP.
If the exponent in the scientific notation is bigger than 13 or smaller than -4, PHP will use scientific representation when printing floats.
Examples:
echo 0.0001; // 0.0001;
echo 0.00001; // 1.0E-5
// 14 digits
echo 10000000000000; // 10000000000000
// 15 digits
echo 100000000000000; // 1.0E+14
See float vs. double precision
That number is too big to fit into a 32 bit integer so PHP is storing it in a float.
See the integer overflow section in the php manual.
On the off chance that you need really big integers, look into GMP.
PHP cannot handle integers that big, and therefore treats them as floats. Floats are typically represented in scientific notation to take into account the inaccuracies past a certain number of significant digits.
The number is too big to be stored as integer by PHP on your platform,
so it is stored as a floating-point number.
The rules of conversion to string are different for float-numbers and integers.
Try the following:
var_dump(100000000000000);
echo(is_int(100000000000000) ? 'an integer' : 'not an integer');
Output:
float(1.0E+14)
not an integer
Any number larger than PHP's built-in integer size is stored and represented as a float.
To format a number in a particular way on output, use a function such as printf .

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

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);

PHP money string conversion to integer error

I have a small financial application with PHP as the front end and MySQL as the back end. I have ancient prejudices, and I store money values in MySQL as an integer of cents. My HTML forms allow input of dollar values, like "156.64" and I use PHP to convert that to cents and then I store the cents in the database.
I have a function that both cleans the dollar value from the form, and converts it to cents. I strip leading text, I strip trailing text, I multiply by 100 and convert to an integer. That final step is
$cents = (integer) ($dollars * 100);
This works fine for almost everything, except for a very few values like '156.64' which consistently converts to 15663 cents. Why does it do this?
If I do this:
$cents = (integer) ($dollars * 100 + 0.5);
then it consistently works. Why do I need to add that rounding value?
Also, my prejudices about storing money amounts as integers and not floating point values, is that no longer needed? Will modern float calculations produce nicely rounded and accurate money values adequate for keeping 100% accurate accounting?
If you want precision, you should store your money values using the DECIMAL data type in MySQL.
Your "prejudices" about floats will never be overcome - it's fundamental to the way they work. Without going into too much detail, they store a number based on powers of two and since not all decimal number can be presented this way, it doesn't always work. Your only reliable solution is to store the number as a sequence of digits and the location of the decimal point (as per DECIMAL type mentioned above).
I'm not 100% on the PHP, but is it possible the multiplication is converting the ints to floats and hence introducing exactly the problem you're trying to avoid?
Currency/money values should never be stored in a database (or used in a program) as floats.
Your integer method is fine, as is using a DECIMAL, NUMERIC or MONEY type where available.
Your problem is caused by $dollars being treated as a float and PHP doesn't have a better type to deal with money. Depending on when $dollars is being assigned, it could be being treated as a string or a float, but is certainly converted to a float if it's still a string for the * 100 operation if it looks like a float.
You might be better off parsing the string to an integer "money" value yourself (using a regex) instead of relying on the implicit conversions which PHP is doing.
The code you posted does the multiplication first, forcing a floating point calculation that introduces error, before converting the value to an integer. Instead, you should avoid floating point arithmetic entirely by reversing the order. Convert to integer values first, then perform the arithmetic.
Assuming previous code already validated and formatted the input, try this:
list($bills, $pennies) = explode('.', $dollars);
$cents = 100 * $bills + $pennies;
Your prejudice against floating point values to represent money is well founded because of truncation and because of values being converted from base-10 to base-2 and back again.
Casting does not round() as in round-to-nearest, it truncates at the decimal: (int)3.99 yields 3. (int)-3.99 yields -3.
Since float arithmetic often induces error (and possibly not in the direction you want), use round() if you want reliable rounding.
You should never ever store currency in floating point, because it always get results you don't expect.
Check out php BC Maths, it allow you to store your currency as string, then perform very high precision arithmetic on them.
Instead of using
$cents = (integer) ($dollars * 100);
you may want to try to use:
$cents = bcmul($dollars, 100, 2);
When converting from float to integer, the number will be rounded towards zero (src).
Read the Floating point precision warning.
There's no point in storing money as integer if you enter it through a floating point operation (no pun intended). If you want to convert from string to int and be consistent with your "prejudice" you can simply use string functions.
You can use an arbitrary precision library to divide by 10 (they handle numbers internally as strings), e.g. bcdiv() or gmp_div_q(), but of course, you could have also used it from the beginning for all the math.
Or you can use plain string functions:
<?php
// Quick ugly code not fully tested
$input = '156.64';
$output = NULL;
if( preg_match('/\d+(\.\d+)?/', $input) ){
$tmp = explode('.', $input);
switch( count($tmp) ){
case 1:
$output = $tmp[0];
break;
case 2:
$output = $tmp[0] . substr($tmp[1], 0, 2);
break;
default:
echo "Invalid decimal\n";
}
}else{
echo "Invalid number\n";
}
var_dump($output);
?>

Categories