Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save djD-REK/068cba3d430cf7abfddfd32a5d7903c3 to your computer and use it in GitHub Desktop.
Save djD-REK/068cba3d430cf7abfddfd32a5d7903c3 to your computer and use it in GitHub Desktop.
console.log(Number(Math.round(1.005 + "e2") + "e-2")) // 1.01
const roundAccurately = (number, decimalPlaces) => Number(Math.round(number + "e" + decimalPlaces) + "e-" + decimalPlaces)
console.log(roundAccurately(1.005, 2)) // 1.01
@velusgautam
Copy link

const roundAccurately = (number, decimalPlaces) => Number(Math.round(Number(number + "e" + decimalPlaces)) + "e" + decimalPlaces * -1);

console.log(roundAccurately(23456789.32452342345, -5)) // 23500000

@hamidgasmi
Copy link

This will not work if the number is already in exponential notation :(

@DoctorDerek
Copy link

@hamidgasmi Nope! JavaScript's built-in math isn't great if you actually need precision or are working with exponential notation. I'd recommend using a library. MathJS is a good place to start. https://mathjs.org/

@y-a11y
Copy link

y-a11y commented Apr 26, 2021

Can anyone help explain what 'e' and 'e-' means in this scenario? I tried it out on code.org and I think it multiplies the value by 10 but I don't understand how the composition of the code can round. Thank You!

@y-a11y
Copy link

y-a11y commented Apr 26, 2021

@DoctorDerek
Copy link

The lower case e is exponential notation, so 10 to the power of positive 2 or minus 2.

Since the built-in rounding function only works on the first decimal place, you can move the decimal point (with the e notation), round, and move the decimal point back.

I'd recommend trying each piece of the code individually, reading the docs on Math.round, and just completely avoiding this use case if it doesn't make sense to you.

Again, the "right" solution here would be to use something more robust. Math.round(1.005) is 1, not 1.01 or 1.0 as you might expect. @y-a11y

@y-a11y
Copy link

y-a11y commented Apr 26, 2021

@DoctorDerek Thank you so much! This makes a lot more sense now

@cccabdalla
Copy link

@hamidgasmi Nope! JavaScript's built-in math isn't great if you actually need precision or are working with exponential notation. I'd recommend using a library. MathJS is a good place to start. https://mathjs.org/

great, thanks.

very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment