Reputation: 1304
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.
Upvotes: 0
Views: 706
Reputation: 146191
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);
Upvotes: 0
Reputation: 27855
You are over complicating it.
It just requires
parseFloat(lineCost).toFixed(2);
Here is a demo fiddle.
Upvotes: 1
Reputation: 152216
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));
Upvotes: 1