Numbers in JavaScript
In this article, we will learn about how numbers are represented in JS and some of their weird behaviours.
Only one datatype
Unlike other popular programming languages like Java and Python, JavaScript does not have a distinct datatype for integers and floats. JS stores whole numbers as well as floats as 64-bit double precision floating point numbers (also known as "double").
const num1 = 2; // 64-bit double const num2 = 3.14; // 64-bit double
Bitwise operations in JS
When it comes to bitwise operations though, a double is first converted to a 32-bit signed integer, after which the bitwise operations are performed. Let's take the example of 4 | 1
4 | 1 // 4 = 00000000000000000000000000000100 (32 bit) // 1 = 00000000000000000000000000000001 (32 bit) // 4 | 1 = 00000000000000000000000000000101 (32 bit)
In this case, 4 and 1 which are 64-bit floats by default, are first converted to 32-bit signed integers, after which, the bitwise operation is carried out. This results in 5 which is a 32-bit signed integer, which gets converted to a double later.
Weird arithmetic behaviour
Operations involving decimals do not behave as expected due to limitations of floating point arithmetic. Let's try a simple calculation -
0.1 + (0.2 + 0.3) = 0.6 (0.1 + 0.2) + 0.3 = 0.6000000000000001
One should be aware of this behaviour when working with cases like monetary calculations.
Edit - It should be noted that this behaviour is not specific to JS, operations involving doubles are tricky in other languages too.
Such cases should be handled carefully in areas like Data Science. You can read more about it in the official Python docs.
Summary
- There is only one datatype to store numbers in JS
- During bitwise operations, all 64-bit doubles are first converted to 32-bit signed integers first
- Arithmetic operations can act weird when dealing with decimal numbers
Well since JS is not built to do data analytics, i think it is fine :) always round off numbers to avoid displaying 60.0000001% :P