obizya
Last Updated: February 25, 2016
·
1.092K
· remybach

Rounding a number to 2 decimal places only if there are decimal places

I couldn't find this done like this anywhere so here's my solution:

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'