0

I have this JavaScript function (see below). It only return whole number, it only works when I inputted a whole number. But when I inputted decimal value it doesn't work.

What should I do to handle decimal value?

function calc()
{
var license=parseInt(document.getElementById("license").value);
var service=parseInt(document.getElementById("service").value);
var amount=parseInt(license)+parseInt(service);

var mult=service*(parseInt(document.getElementById("preterms").value) / 100);
var mult1=service*(parseInt(document.getElementById("blueterms").value) / 100);
var mult2=service*(parseInt(document.getElementById("configterms").value) / 100);

document.getElementById("amount").value = amount;
document.getElementById("pre").value = mult;
document.getElementById("blue").value = mult1;
document.getElementById("config").value = mult2;

}

Thanks in advance.

4

3 回答 3

1

更改parseIntparseFloat,例如

var license=parseInt(document.getElementById("license").value);

var license=parseFloat(document.getElementById("license").value);
于 2013-05-15T04:04:05.497 回答
0

看起来人们建议使用parseFloat. 您可能会遇到的下一个问题是格式化输出。您可以使用toFixed固定小数位数输出百分比:

(12.34567).toFixed(2)
// => "12.35"
于 2013-05-15T04:46:41.807 回答
0

由于您使用的是十进制值,因此您需要使用parseFloat而不是parseInt

前任:

function calc() {
    var license = parseFloat(document.getElementById("license").value);
    var service = parseFloat(document.getElementById("service").value);
    var amount = parseFloat(license) + parseFloat(service);

    var mult = service * (parseFloat(document.getElementById("preterms").value) / 100);
    var mult1 = service * (parseFloat(document.getElementById("blueterms").value) / 100);
    var mult2 = service * (parseFloat(document.getElementById("configterms").value) / 100);

    document.getElementById("amount").value = amount;
    document.getElementById("pre").value = mult;
    document.getElementById("blue").value = mult1;
    document.getElementById("config").value = mult2;

}
于 2013-05-15T04:04:31.553 回答