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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With