How to parse float with two decimal places in javascript?
I have the following code. I would like to have it such that if price_result equals an integer, let’s say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.
price_result = parseFloat(test_var.split(‘$’)[1].slice(0,-1));
Solutions/Answers:
Solution 1:
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
Solution 2:
When you use toFixed
, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
Solution 3:
If you need performance (like in games):
Math.round(number * 100) / 100
It’s about 100 times as fast as parseFloat(number.toFixed(2))
Solution 4:
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
Solution 5:
If your objective is to parse, and your input might be a literal, then you’d expect a float
and toFixed
won’t provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
Solution 6:
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it’s safe