我试图将此脚本的结果赋予2位小数。它们实际上已经有2个小数,但是当我将最后2个加在一起(35.75 + 16.06)时,我得到€51.629999999999995作为输出。
这是我的剧本;
<!DOCTYPE html>
<html>
<head>
<script>
function bereken() {
var total = 0;
if (document.forms[0].boek1.checked) {
total += 27.74;
}
if (document.forms[0].boek2.checked) {
total += 26.13;
}
if (document.forms[0].boek3.checked) {
total += 35.57;
}
if (document.forms[0].boek4.checked) {
total += 16.06;
}
totalP = "€" + total
document.forms[0].total.value = totalP;
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="boek1">Boek 1<br>
<input type="checkbox" name="boek2">Boek 2<br>
<input type="checkbox" name="boek3">Boek 3<br>
<input type="checkbox" name="boek4">Boek 4<br>
<div><input type="button" value="Totaal" onclick="bereken()" /><br><br>
<input type="text" value="€" name="total" size="5" />
</form>
</body>
你们有谁知道我做错了吗?
答案 0 :(得分:1)
使用Math.round()
:
document.forms[0].total.value = Math.round(parseFloat(totalP.substr(1)) * 100)/100;
工作预览
还有其他方法可以做到这一点。您也可以使用.toFixed(n)
:
document.forms[0].total.value = parseFloat(totalP.substr(1)).toFixed(2);
答案 1 :(得分:0)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
结帐函数decimalAdjust。效果很好
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}