Today I Learned

hashrocket A Hashrocket project

Be Careful with JavaScript Numbers

Today I Learned that you need to be careful when working with numbers in JavaScript. This is because of the way that JavaScript implements the Number type.

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values ...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Take for example the following Ruby snippet:

> 2 / 5
=> 0

Our division here returns 0, which is what I expected. And if you want the remainder, you can get it with the modulus operator %

Now here's the same snippet in JavaScript, which returns a double-precision number that is not zero

> 2 / 5
0.5

If you're looking to do integer-like division in JavaScript, here's a few ways you can accomplish that:

> Math.floor(2 / 5)
0

> Math.trunc(2 / 5)
0

> (2 / 5) >> 0
0

Docs

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc

Here's a callback to another JavaScript number TIL 😅

https://til.hashrocket.com/posts/e04ffe1d76-because-javascript

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.