开发者

Javascript parseFloat result

开发者 https://www.devze.com 2023-01-17 23:24 出处:网络
Consider this script. <script type=\"text/javascript\"> document.write(parseFloat(parseFloat(\"97.74\")+parseFloat(\"1.82\")) + \"<br />\");

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

精彩评论

暂无评论...
验证码 换一张
取 消