Rounding decimal numbers using toFixed

I have a little problem with the JavaScript toFixed(2) function.

If I round this decimal number 45.24859 , I get 45.25 with this function.

But my problem is that if I round 10 (it does not have a decimal part), the function will return the decimal number 10.00 .

How can I fix this problem?

My problem: if you enter a number without a decimal part, the function should return a non-decimal number.

+7
javascript rounding
source share
2 answers

Another way to solve this

Demo

. indexOf ()

 function roundNumber(num){ return (num.toString().indexOf(".") !== -1) ? num.toFixed(2) : num; } 


The solution below is not compatible with all browsers.

or

 function roundNumber(num){ return (num.toString().contains(".")) ? num.toFixed(2) : num; } 

. contains () Strike>

+7
source share

We can check whether the number is decimal or not with this. Check if the number has a decimal number ...

So, combining this function, you can use

 function roundNumber(num){ return num % 1 != 0 ? num.toFixed(2) : num; } 

Or I think the best option would be to use

 Math.round(num * 100) / 100 
+6
source share

All Articles