Last Updated: February 25, 2016
·
3.672K
· 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'

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside