Volume set to decimal in SoundService changes by a tiny fraction

I’ve come across this bug when trying to make a mute button for a game I’m working on. The Volume property of a Sound object called “GameMusic” located in SoundService is set to 0.2 by default. Whenever I try to access the Volume variable via a localscript, this happens:image

I’m not sure when this started happening because it’s been happening ever since I started the mute button which was a couple days ago. I’ve run into something like this before but it’s annoying that it’s changing even though I’m not setting the volume of that Sound object anywhere else in the game.

This is a problem because I use the volume to check whether or not the sound is playing, because in my game it’s easier than doing :Play() and :Resume() because of the way my scripts work.

There is no solution to this problem. It’s a general problem with all decimal numbers in computers called floating point inaccuracy. It’s not possible for the computer to have the number 0.2, so instead it has 0.20000000298023. When you set it to 0.2, it actually gets set to 0.20000000298023.

These types of numbers are called floating point numbers, or floats for short.


Instead of checking if your volume ==, you should check if it’s near the number you’re wanting to check.

For example:

if math.abs(GameMusic.Volume - 0.2) < 0.01 then
    -- treat volume as if it's 0.2
end

You can turn this into a function for easier use:

function fEquals(float, equal, maxDiff)
    return math.abs(float - equal) < (maxDiff or 0.01)
end

if fEquals(GameMusic.Volume, 0.2) then
    -- treat volume as if it's equal to 0.2
end
2 Likes
if math.abs(GameMusic.Volume*10)/10 == 0.2 then
-- code stuffs
end

So, this is also generally a bad idea.
For something like volume there are very few cases where you need to know the actual value.
Chances are, you just need to keep a variable like isMuted = false. Then just set your volume like this:

function toggleIsMuted()
    isMuted = not isMuted
    sound.Volume = isMuted and 0 or 0.2
end

For this specifically, there’s Sound.Playing.

1 Like

I was thinking about this as I wrote my response but I figured I would keep my response short and simple. I’m glad you brought it up anyway.

@EncodedLua you should definitely do something like this rather than relying on what the Volume property is. There may be cases in the future where the fEqual function may be useful, though, but it’s not the optimal solution here.

1 Like

Yea that’s basically what I ended up doing after the solution response. But thank you for the response.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.