Rounding a number to 2 decimal places only if there are decimal places Posted on: 2012-05-30

I couldn’t find it done this way anywhere else, so I thought I’d share:

var number = 3.14159;

// If there are decimal places
if ( number % 1 !== 0 ) {
    // Cast to string and return the last two numbers.
    number = number.toFixed(2);
}

// number is now '3.14'

If you really wanted to have a one liner, you could use a ternary operator and rely on the fact that 0 is falsy:

number = (number % 1) ? number.toFixed(2) : number;

Nice and easy!