user88432
user88432

Reputation: 417

Number decimal issue

I am having problem that is not calculating the total correctly.

I am getting total value is 24, I am expecting 25.60000

What did I do wrong?

Example:

var a = "12.80000"; //Set as string deliberately
var b = "12.80000";

var total = 0;
total += roundAmount(parseInt(a), 5);
total += roundAmount(parseInt(b), 5);

console.log(total); 

function roundAmount(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

Upvotes: 1

Views: 66

Answers (3)

Andrew T
Andrew T

Reputation: 193

Your parseInt() functions are rounding the numbers to 12 before they are added, instead use parseFloat(). This works for me:

var a = "12.80000"; //Set as string deliberately
var b = "12.80000";

var total = 0;
total += roundAmount(parseFloat(a,10), 5);
total += roundAmount(parseFloat(b,10), 5);

console.log(total); 

function roundAmount(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

Upvotes: 0

Charles Wiktenschtien
Charles Wiktenschtien

Reputation: 75

Your problem is that you're converting a floating point number to an integer with parseInt() so your computer stores "12.8000" as an integer type (i.e. 12). Try using the parseFloat() function instead.

Upvotes: 0

epascarello
epascarello

Reputation: 207511

You are chopping off the decimal with parseInt, you want parseFloat.

var a = "12.80000"; //Set as string deliberately
var b = "12.80000";

var total = 0;
total += roundAmount(parseFloat(a), 5);
total += roundAmount(parseFloat(b), 5);

console.log(total); 

function roundAmount(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

You are not going to get the extra trailing zeros in the output, if you want them, you need to use toFixed(5) when you output it.

Upvotes: 2

Related Questions