7

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.

Jongware
  • 22,200
  • 8
  • 54
  • 100
rplg
  • 232
  • 3
  • 12
  • possible duplicate of [Round up to 2 decimal places in javascript](http://stackoverflow.com/questions/11832914/round-up-to-2-decimal-places-in-javascript) – Sarath Nov 04 '13 at 11:48
  • please note that this has NOTHING to do with jQuery in the slightest. – Sterling Archer May 19 '14 at 15:08

2 Answers2

7

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()

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
6

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
Community
  • 1
  • 1
Sarath
  • 9,030
  • 11
  • 51
  • 84