-1

I'm trying to decrement "0.01" from a number, it works fine the first time, but when I try to decrement one more time it adds some extra numbers.

Here is my JavaScript code:

function decrement() {

        var credits_sidebar = $('#credits_sidebar').html();
        var credits_update = credits_sidebar - 0.01;
        $("#credits_sidebar").fadeOut('');
        $("#credits_sidebar").html(credits_update);
        $("#credits_sidebar").fadeIn(''); 

}

If you click once on the decrement button it works, but if you click another time, the number will be "95.97999999999999" it should be 95.98 instead.

Here's an example JsFiddle:

https://jsfiddle.net/rozvnay1/

Josh
  • 1

4 Answers4

2
var credits_update = (credits_sidebar - 0.01).toFixed(2)

JSFiddle demo: https://jsfiddle.net/8eakhn4L/1/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
0

This is a problem with floating point value representation. You should consider using

Math.round((credits_sidebar - 0.01)* 100)) / 100

Praveen S
  • 104
  • 11
0

This behavior is normal and expected because of the way floating point math is done in JavaScript.

However what you simply can do is multiply your number by a factor of 100 to make it a whole number that needs to be decremented then you can do the decrement and divide the result by 100 to get the correct decimal answer.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You need to update this for working of code:

var credits_update = (credits_sidebar - 0.01).toFixed(2);
Andrew
  • 67
  • 2
  • 8