Thanks for checking this out people.
I’m learning PHP from “PHP for Absolute Beginners” book but can’t figure why I get the wrong answer from the code below:
<?php
$amt1=2.55;
$amt2=3.55;
$total= $amt1 + $amt2;
echo'<br/>The total is $'. $total;
printf('<br/>The total is %.21f', $total);
?>
I get 6.099999999999644729 not 6.1000… (just imagine 20 zeros)
Using Eclipse/XAMP/MAC OSX Lion How can the computer lie like that- or (more likely) how can I keep it honest by writing better code?
floats have limited precision. floats cannot represent all numbers (one or more of
2.55,3.55or6.10is not representable precisely). In situations where very high or exact precision is required, floats are the wrong data type. You’re best bet here is probably round.(On a technical note, “floats have limited precision” is a bit wrong. What might be more accurate is “floats can only represent some numbers exactly. Some numbers are impossible to represent with exact precision with a float.”)