You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
Answer from Mahesh Velaga on Stack OverflowYou can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
EDIT:
https://jsperf.app/kowulu
You have to call toFixed after parseFloat:
parseFloat(yourString).toFixed(2)
Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
- Either use data as a string or
- Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2): Here 2 is the number of digits up to which we want to round this number.
2022, native, without library, modern browser, clear and readable.
function round(
value,
minimumFractionDigits,
maximumFractionDigits
) {
const formattedValue = value.toLocaleString('en', {
useGrouping: false,
minimumFractionDigits,
maximumFractionDigits
})
return Number(formattedValue)
}
console.log(round(21.891, 2, 3)) // 21.891
console.log(round(1.8, 2)) // 1.8, if you need 1.80, remove the `Number` function. Return directly the `formattedValue`.
console.log(round(21.0001, 0, 1)) // 21
console.log(round(0.875, 3)) // 0.875