Question

I am loading numeric values to 2 decimal places using Javascript. All values seem okay, apart from £299.90 and £499.90, which loads as £299.9 and £499.9

Current code:

//ROUNDING FUNCTION
function round(num, decimals) {
     return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
}

//LOADING VALUES - Line cost variable is £49.99/£29.99 * 10
jQuery(".content").html("£" + round(lineCost, 2));

What I have tried:

jQuery(".content").html(parseFloat(lineCost * 100) / 100).toFixed(2);

jQuery(".content").html(Number(lineCost).toFixed(2));

Any ideas?

Thanks.

Was it helpful?

Solution

You can try with toFixed method on a float/integer value:

var value = 0.127456;
    value.toFixed(2);

Output:

0.13

In your case:

jQuery(".content").html("£" + lineCost.toFixed(2));

If lineCost is a string, parse it to float:

jQuery(".content").html("£" + parseFloat(lineCost).toFixed(2));

OTHER TIPS

You are over complicating it.

It just requires

parseFloat(lineCost).toFixed(2);

Here is a demo fiddle.

Actually rounding means to convert a number like 10.5 to 11 or 12.49 to 12 so you should not round the number if you want to use a float with decimals, instead you should just use something like this:

var lineCost = 12.5;
parseFloat(lineCost).toFixed(2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top