Explain Codes LogoExplain Codes Logo

How do you round to one decimal place in JavaScript?

javascript
rounding
math-functions
precision
Alex KataevbyAlex Kataev·Dec 29, 2024
TLDR

For immediate rounding to one decimal place, combine .toFixed(1) with Number:

const rounded = Number(2.345.toFixed(1)); // 2.3

The catch? Be prepared to deal with a string value when you use toFixed.

Deep dive into rounding methods in JavaScript

It's time to unpack our JavaScript toolkit and explore various options for tackling our rounding task:

The simple path: Math.round() with scaling

Scale your numbers up by the power of tens equivalent to the desired decimal places, then round off and scale down. A simple, yet effective solution.

const roundOneDecimal = num => Math.round(num * 10) / 10; // Where did the zero go? '1 ÷ 10' sent it on vacation.

Champion of consistency: toFixed()

If consistency is your beat, then the toFixed() method is your rhythm. Giving it a '1' ensures one decimal place, even for whole numbers:

console.log((2.345).toFixed(1)); // "2.3" — nice! console.log((2).toFixed(1)); // "2.0" — and, it never forgets the .0

Remember: toFixed() is a string enthuasiast, so switch types when mathematical operations loom:

const toNumber = parseFloat((2.345).toFixed(1)); // 2.3, a number to reckon with.

For the control freaks: A custom round function

In JavaScript, we are free to build our own round function. With Math.pow(), we can easily adjust the precision of our function:

const customRound = (num, decimals) => { const factor = Math.pow(10, decimals); return Math.round(num * factor) / factor; // Because who doesn't like tailoring their own wardrobe? };

Guard rails: Managing edge cases and negative numbers

Watch out for bankers' rounding and negative numbers. Remember to be mindful of your math:

const roundNegative = num => -Math.round(-num * 10) / 10; // Did I hear someone say 'Recycling?'

Library to the rescue: lodash

Meet _round, part of the versatile lodash library. It doesn't discriminate; positive, negative — it's all just numbers.

const rounded = _.round(2.345, 1); // Everyone deserves some TLC. Even numbers.

Precision pitfalls and solutions

Multiplying by ten might seem like a good idea until you run into floating-point precision problems. How to fix? Math.pow(), of course:

const rounder = (num, places) => Math.round(num * Math.pow(10, places)) / Math.pow(10, places); // NO PAIN, more gains.

Which method, when?

Choose the right tool for the job by understanding what each method is best suited for:

Straightforward rounding

  • One-off rounding: Number(2.86.toFixed(1))
  • Quicker than a sprinter on race day!

Keeping it professional

  • Currency: toFixed() to keep those decimal places in sight.
  • Fort Knox standard precision.

Data crunching

  • Further computations: Use parseFloat() after toFixed().
  • Who said we can't have numbers and strings playing nice?

Control freak mode: Precision

  • Flexibility: A custom rounding function lets you choose the number of decimal places.
  • Precision is the key!

In for the long haul

  • Tough customers: For consistent and reliable rounding with both positives and negatives, trust Lodash.
  • Never let inconsistency dull your shine!