php float calculation 2 decimal point
Try sprintf
("%.2f", $c);
Floating point numbers are represented in IEEE notation based on the powers of 2, so terminating decimal numbers may not be a terminating binary number, that's why you get the trailing digits.
As suggested by Variable Length Coder, if you know the precision you want and it doesn't change (e.g. when you're dealing with money) it might be better to just use fixed point numbers i.e. express the numbers as cents rather than dollars
$a = 3456;
$b = 3455;
$c = $b - $a;
sprintf ("%.2f", $c/100.0);
This way, you won't have any rounding errors if you do a lot of calculations before printing.
Show a number to two decimal places
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
PHP float with 2 decimal places: .00
A float doesn't have 0
or 0.00
: those are different string representations of the internal (IEEE754) binary format but the float is the same.
If you want to express your float as "0.00", you need to format it in a string, using number_format :
$numberAsString = number_format($numberAsFloat, 2);
php Determine a float variable has two decimal places
Everybody is dancing around the fact that floating point numbers don't have a number of decimal places in their internal representation. i.e. in float 100 == 100.0 == 100.00 == 100.000 and are all represented by the same number, effectively 100 and is stored that way.
The number of decimal places in this example only has a context when the number is represented as a string. In which case any string function that counts the number of digits trailing the decimal point could be used to check.
Cast int to float, two decimal values in PHP
If you're just using the regular equality operator (==
) instead of the type-safe equality operator (===
) you shouldn't have any problems.
Comparing a double to an int with the same values:
$i = 20;
$m = 20.00;
gettype($i); // integer
gettype($m); // double
$i == $m; // true;
$i === $m; // false, $m is a double and $i is an integer.
If we would like to fix that, however, we just need to do:
$i = (double)$i;
gettype($i); // double
$i === $m; // true!
PHP - Floating Number Precision
Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats a
and b
, (a+b)-b != a
. This applies to any language using floats.
Since floating point are binary numbers with finite precision, there's a finite amount of representable numbers, which leads accuracy problems and surprises like this. Here's another interesting read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Back to your problem, basically there is no way to accurately represent 34.99 or 0.01 in binary (just like in decimal, 1/3 = 0.3333...), so approximations are used instead. To get around the problem, you can:
Use
round($result, 2)
on the result to round it to 2 decimal places.Use integers. If that's currency, say US dollars, then store $35.00 as 3500 and $34.99 as 3499, then divide the result by 100.
It's a pity that PHP doesn't have a decimal datatype like other languages do.
PHP Adding 2 decimal points numbers (money) gives wrong results in total amount
Indeed, floating point numbers are not precise.
Either calculate in cent (multiply by 100 and calculate in integers), or calculate in strings using BC Math.
Related Topics
Use Variable as Function Name in PHP
Android: Uploading Image on Server with PHP
Php: Variable-Length Argument List by Reference
Pass Value from HTML Form to PHP Without Submitting the Form
Best Way to Check a Empty Array
Multiple Radio Button Array for PHP Form
Hide Added to Cart Message in Woocommerce
Sort Array by Value Alphabetically PHP
Setting a Cookie in an Ajax Request
Why Is the Semicolon Optional in the Last Statement in PHP
Laravel Change Connection Dynamically
Why Does (0 == 'Hello') Return True in PHP
Fatal Error: Uncaught Argumentcounterror: Too Few Arguments to Function
Is There a Function Similar to Settimeout() (Javascript) for PHP
Differencebetween $_Files["File"]["Type"] and End(Explode(".", $_Files["File"]["Name"]))
PHP Date - Get Name of the Months in Local Language