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'
Written by Rémy Bach
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#