考虑这个脚本.
<script type="text/javascript">
document.write(parseFloat(parseFloat("97.74")+parseFloat("1.82")) + "<br />");
</script>
Run Code Online (Sandbox Code Playgroud)
为什么结果是99.55999999999999?我怎样才能获得预期的输出?
欢迎来到浮点数:)
你可以使用.toFixed(numOfDecimalPlaces)它,例如:
document.write((parseFloat("97.74")+parseFloat("1.82")).toFixed(2) + "<br />");
Run Code Online (Sandbox Code Playgroud)
输出.toFixed()是一个字符串,四舍五入到指定的小数位数.