What’s wrong with first impression?

Tags:
JavaScript
Addition of (3 + .47) gives 3.4699999999998 But addition of (3 + .46) gives 3.46 What is wrong with first expression? Why first expression is not evaluated to 3.47? [Issued faced on IE as well as on Firefox]

Answer Wiki

Thanks. We'll let you know when a new response is added.

This is an issue with how floating point numbers are handled.

0.47 is converted from a string into binary to be manipulated. Then you do stuff to it. Finally it is converted back into a string (in base 10) to be displayed. The problem is that some decimal numbers (floating points) can’t be exactly defined in a finite number of binary places. This is exactly the same problem you have with representing 1/3 in decimal notation in base10 (0.333333333…)

A lengthy explanation of a similar bug in excel where it displays the incorrect result of 77.1*850 can be seen here: Explaining the Excel Bug

Discuss This Question: 1  Reply

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • MarkWPF
    One way to get around this in typed languages is to use a decimal type. Could you co-erce the variable to be decimal in javascript?
    15 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following