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
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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#