Explain Codes LogoExplain Codes Logo

How to round float numbers in javascript?

javascript
prompt-engineering
functions
performance
Alex KataevbyAlex Kataev·Oct 25, 2024
TLDR

For quick rounding of float to two decimal places, use:

const round = (num) => Math.round(num * 100) / 100; console.log(round(5.123)); // "Bam!" It's 5.12 now!

If the mission is to round to n decimal places, just change 100 with 10**n.

Precision with toFixed method

The JavaScript toFixed() method provides a handy way to round a number to a set number of decimal places and return it as a string.

let rounded = (num, decimals) => Number(num.toFixed(decimals)); console.log(rounded(6.688689, 2)); // "Smooth Operator" — it's 6.69 now!

Keep in mind that toFixed() is like that nice friend who always rounds you up when you're 5 or more and down when you're less.

Rounding techniques and unexpected guests

Four roads to Rome...

In JavaScript, we have several ways to "Rome":

  • Math.round(num) - takes the all-rounder path, rounding to the nearest integer or specified decimal place.
  • Math.ceil(num) - always takes the high road!
  • Math.floor(num) - stays humble, friends. Always rounds down!

Manipulate decimal places by multiplying and dividing by 10^n for each of them.

...And uninvited guests

As in every sweet party, JavaScript's floating-point numbers may introduce surprise elements. These small inaccuracies can become the uninvited guests when performing arithmetic operations. Always have the bouncer — extra checks or precision libraries — ready!

Show off with a custom rounding function

For some parties, you may need to DJ your own rounding function. Let me introduce decimalAdjust, for those who like more control on the mix:

function decimalAdjust(type, value, exp) { // If exp is undefined or equals zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If value isn't a number or exp isn't an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // Shuffle value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); // Un-shuffle value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); } // Decimal bebop const round10 = (value, exp) => decimalAdjust('round', value, exp); // This will make you the "hip" at the party!

Performance comparison: are you quick enough?

Comparing performance is like asking who is the fastest runner. The toFixed() method might not be Usain Bolt due to the transformation to and from a string. Like a seasoned runner, it can be more efficient to multiply by powers of 10, use Math.round, and then divide by the power of 10.

Conduct your own Olympics with benchmarks to find out:

console.time('Using toFixed'); for (let i = 0; i < 100000; i++) { (Math.PI).toFixed(2); } console.timeEnd('Using toFixed'); // Finish time! console.time('Using multiply/divide'); for (let i = 0; i < 100000; i++) { Math.round(Math.PI * 100) / 100; } console.timeEnd('Using multiply/divide'); // Did we beat Usain?

Rounding: what the textbooks don't tell you

The Number.toPrecision() method offers an undercover way to round a float to a certain level of overall precision:

let num = 5.123456; console.log(+num.toPrecision(4)); // "In stealth mode" — it's 5.123 now!

The unary + operator is your secret agent to swiftly get back to the number from a string.

Beyond the basic party tools

There are plenty of "party planning" npm packages for rounding floats in JavaScript. Packages like mathjs, decimal.js, 'expected-round' package. Each of them is like a party specialist, ready to make your rounding party a blast without reinventing the wheel.

Leaving no stone unturned

When handling financial or scientific computations, it's essential to test your rounding solution with multiple cases to ensure expected results.