Consider this script.
<script type="text/javascript">
document.write(parseFloat(parseFloat("97.74")+parseFloat("1.82")) + "<br />");
<开发者_运维问答/script>
Why is the result 99.55999999999999 ? And how can I get the expected output?
Welcome to floating point numbers :)
You can use .toFixed(numOfDecimalPlaces)
for this, for example:
document.write((parseFloat("97.74")+parseFloat("1.82")).toFixed(2) + "<br />");
The output of .toFixed()
is a string, rounded to the specified number of decimal places.
It's a rounding error, due to the computer working in base 2 whilst your brain works in base 10.
Try this:
var x = parseFloat(parseFloat("97.74")+parseFloat("1.82");
document.write(Math.round(x * 100) / 100);
精彩评论