I have been a back-end developer for some time now but I have decided to learn some front end (JavaScript) stuff too! I know, you must be thinking , it’s 2017, why on earth have I decided to learn vanilla JavaScript ! May be I should be learning frameworks like ReactJS, Angular, Vue. Sure, why not, that is the idea but I would like to get the basics (JavaScript) right first.
I have been learning the basics of JavaScript and it turns out that quite a number of people mention a few WTF’s with JavaScript . One of them being: 0.1 + 0.2 !== 0.3. If you are in a state of shock now, well , you should be there for a few more seconds….
Time to come out now ! Well, this is not a problem with JavaScript . Don’t believe me ?
Let us try the same thing in a different language:
Java:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FloatingPoint { | |
public static void main(String[] args) { | |
System.out.println(0.1 + 0.2); | |
} | |
} |
Output
0.30000000000000004
So obviously this is not equal to 0.3
Right way to do it : Using BigDecimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
public class FloatingPointCorrected { | |
public static void main(String[] args) { | |
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2"))); | |
} | |
} |
If you tried the same in Python, you will still get the same unexpected result.
Right way to do it in JavaScript : Using toFixed function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+(0.1 + 0.2).toFixed(1); |
Using the toFixed function from Number object helps us in setting the number of digits after the decimal point.It returns a string and hence we need the + operator at the beginning.
So let us not give JavaScript, the language, criminal status for an offense it never committed !
But why is 0.1 + 0.2 ! = 0.3, take a look here : Floating point Math
Conclusion
Let us not find incorrect reasons to criticize the language. Learning JavaScript so far has been a fun learning experience. Of course there have been some WTF moments as well.
JavaScript is powerful ! I urge you to learn it.