DEV Community

Cover image for JavaScript Interview Question #14: 0.1 + 0.2 = ?
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JavaScript Interview Question #14: 0.1 + 0.2 = ?

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

Top comments (4)

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
Pacharapol Withayasakpunt

It's not only JavaScript.

0.30000000000000004.com/

Collapse
 
bruce_taotao profile image
bruce_taotao

yep

Collapse
 
sonyarianto profile image
Sony AK

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