Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding decimal numbers using toFixed

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.

like image 241
rplg Avatar asked Oct 29 '13 06:10

rplg


2 Answers

Another way to solve this

DEMO

.indexOf()

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


Below solution not compatible with all browsers.

or

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

.contains()

like image 85
Tushar Gupta - curioustushar Avatar answered Oct 23 '22 08:10

Tushar Gupta - curioustushar


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
like image 6
Sarath Avatar answered Oct 23 '22 06:10

Sarath