JavaScript adding decimal numbers issue
This question already has an answer here:
Use toFixed
to convert it to a string with some decimal places shaved off, and then convert it back to a number.
+(0.1 + 0.2).toFixed(12) // 0.3
It looks like IE's toFixed
has some weird behavior, so if you need to support IE something like this might be better:
Math.round((0.1 + 0.2) * 1e12) / 1e12
function add(){
var first=parseFloat($("#first").val());
var second=parseFloat($("#second").val());
$("#result").val(+(first+second).toFixed(2));
}
DEMO。
This is common issue with floating points.
Use toFixed
in combination with parseFloat
.
Here is example in JavaScript.
链接地址: http://www.djcxy.com/p/27446.html上一篇: 为什么在Javascript中添加两位小数会产生错误的结果?
下一篇: JavaScript添加十进制数字问题