jules
jules

Reputation: 19

function to get percentage in JavaScript and return decimal value

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.

Upvotes: 0

Views: 826

Answers (3)

Adam Sanderson
Adam Sanderson

Reputation: 490

It looks like folks suggested using parseFloat. The next issue you're likely to run into is formatting the output. You can use toFixed to output your percentages with a fixed number of decimals:

(12.34567).toFixed(2)
// => "12.35"

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

Since you are working with decimal values You need to use parseFloat instead of parseInt

ex:

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;

}

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

change parseInt to parseFloat, like

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

to

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

Upvotes: 1

Related Questions