DEV Community

loading...
Cover image for JavaScript Interview Question #14: 0.1 + 0.2 = ?

JavaScript Interview Question #14: 0.1 + 0.2 = ?

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

js-test-14

JavaScript math is weird. What’s the output? True or false?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Inside the computer, all numbers are stored in the Binary Number System.

To keep it simple, it’s the sequence of bits - which are "digits" that can be either 0 or 1.

The number 0.1 is the same as 1/10 which can be easily represented as a decimal number. In binary, it will result in an endless fraction, similar to what 1/3 is in decimal.

All numbers in JavaScript are stored as 64-bit signed floating-point values, and when there’s not enough space to hold the value, the least significant digits are rounded.

This leads us to the fact that in JavaScript 0.1 + 0.2 render 0.30000000000000004 and not 0.3 like you would have obviously thought.

If you're unfamiliar with the Binary Number System I suggest reading this article.


ANSWER: false will be printed on the screen.

Learn Full Stack JavaScript

Discussion (4)

pic
Editor guide
Collapse
lexlohr profile image
Alex Lohr

Every language using IEEE 754 64bit floating point numbers (1 bit sign, 10 bit exponent, 53 bit mantissa) will have the same behavior, JavaScript being no exception.

Collapse
patarapolw profile image
Collapse
bruce_taotao profile image
Collapse
sonyarianto profile image
Sony AK

wow, just know about it :) even there is dedicated domain for it ;)