Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple subtraction bug in Javascript

Tags:

I was shocked to see such a basic subtraction bug in JS, I am sure most of you here would have experienced this issue, please help me with a work around here, All I am doing is subtracting a number from 100 which gives unexpected results, an example is stated below

100 - 99.1 // returns 0.9000000000000057 

Am I doing something wrong here ? :S I am confused

like image 863
Umair Jabbar Avatar asked Mar 01 '11 10:03

Umair Jabbar


2 Answers

Floating point values are never accurate as you expect. You can use Number object to convert this to answer as you need.

Number(100).toFixed(2) - Number(99.1).toFixed(2) 
like image 88
Sachin Shanbhag Avatar answered Oct 12 '22 20:10

Sachin Shanbhag


You are working with floating point numbers, not integers. This is expected.

The reason is that you can't accurately represent numbers like 0.1 and 0.3 in binary. Just like you can't represent 1/3 accruately in decimal form.

like image 41
jrharshath Avatar answered Oct 12 '22 21:10

jrharshath