I have small issue with the JavaScript function toFixed(2)
.
If I round this decimal number 45.24859
, I get 45.25
using this function.
But my problem is, if I round 10
(it has no decimal part), the function will return a decimal number 10.00
.
How can I fix this issue?
My problem is, if enter a number without a decimal part, the function should return a non decimal number.
Another way to solve this
DEMO
.indexOf()
function roundNumber(num){
return (num.toString().indexOf(".") !== -1) ? num.toFixed(2) : num;
}
or
function roundNumber(num){
return (num.toString().contains(".")) ? num.toFixed(2) : num;
}
.contains()
We can check the number is decimal or not with this Check if a number has a decimal...
So combining that you can use this function
function roundNumber(num){
return num % 1 != 0 ? num.toFixed(2) : num;
}
Or I think better option will be to use
Math.round(num * 100) / 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With