3

So I have volume up and down buttons that displays a notification every time the volume is increased.

Volume Up

  function volumeUp() {
    if (currentVolume < .9) {
      currentVolume += .1;
      sound.volume = currentVolume;
      var $toastContent = $('<span>Volume '+ parseInt(currentVolume * 100)+ ' %' + '</span>' );
      Materialize.toast($toastContent, 2000);
    } else {
      alert("Max Vol")
    }
  }

Volume Down

  function volumeDown() {
    if (currentVolume > .1) {
      currentVolume -= .1;
      sound.volume = currentVolume;
      var $toastContent = $('<span>Volume '+ parseInt(currentVolume * 100)+ ' %' + '</span>' );
      Materialize.toast($toastContent, 2000);
    } else {
      alert("Min Vol")
    }
  }

The problem I'm having is, when I get to < 80% it starts to alert as 89 then 99 instead of 90 and 100.

Also when I get to 10% and I decrease it, it shows as 2% not 0%.

Any ideas?

Thank you!

Matt Thomas
  • 865
  • 1
  • 13
  • 27

2 Answers2

3

As Amit mentioned it's about floating point math. If you open the console and declare a variable and initialize it with 0.7 + 0.1 you'll see that it's actual value will be 0.7999999999999999

For your media player it won't make a difference so it's only about displaying this value. You have two options:

1) Work with integers:

function volumeUp() {
  if (currentVolume < 90) {
    currentVolume = currentVolume + 10;
    sound.volume = currentVolume / 100;
    var $toastContent = $('<span>Volume '+ currentVolume+ ' %' + '</span>' );
    Materialize.toast($toastContent, 2000);
  } else {
    alert("Max Vol")
  }
}

2) Apply rounding after each addition:

currentVolume = Math.round((currentVolume + 0.1) * 10) / 10;

or

currentVolume = (parseFloat(currentVolume) + 0.1).toFixed(1); //string representation with one decimal
B0Andrew
  • 1,725
  • 13
  • 19
1

First of all, the below line does not makes sense.

currentVolume = currentVolume += .1;

Either do currentVolume = currentVolume + .1; or currentVolume += .1;

After .9 and below .1 if you want to make an increment or decremenet of 1 instead of 10 then you should do

currentVolume += .01; // Instead of .1 in your volumeUp() function

and

currentVolume -= .01; // Instead of .1 in your volumeDown() function
void
  • 36,090
  • 8
  • 62
  • 107