30-seconds-of-code: Round Number To n Digits

Created on 14 Dec 2017  路  4Comments  路  Source: 30-seconds/30-seconds-of-code

Wanted to gauge interest before creating a PR. Would others consider this clear & useful?

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)

Importantly the above works correctly with all floating point numbers.

// All of the following *should* return 1.01 but *actually* return 1

Number(1.005.toFixed(2))
Math.round(1.005 * 100) / 100
opinions needed question

All 4 comments

Hi, thanks for the interest! I like the idea, was planning to add something like what is mentioned on this SO thread. Basically, round the number only if necessary and omit trailing zeroes. Do you think you can code that, so we can add it?

Of course @Chalarangelo!

The current implementation has the type signature (Number, Number?) => Number so it already only rounds if necessary and omits trailing zeroes (Numbers don't have trailing zeroes)

If you wanted (Number, Number?) => String you can easily just call .toString() on the result

@ecwyne get cracking, we should get this added! 馃槈

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Bruce-Feldman picture Bruce-Feldman  路  4Comments

emelendez picture emelendez  路  4Comments

fejes713 picture fejes713  路  4Comments

Speuta picture Speuta  路  3Comments

Lucien-X picture Lucien-X  路  5Comments