0

For my GDX program I made an Option Menu with two buttons. One of them increases the sound volume, one of them lowers it. It increases / decreases by 0.1 whenever a button is clicked. Here is the code:

soundMButton = new ImageButton(drawableSoundM);
soundMButton.addListener(new ClickListener(){
    @Override
    public void clicked(InputEvent event, float x, float y) {
        if (Constants.soundLevel > 0.0) {
            Constants.soundLevel -= 0.1;
            System.out.println(Constants.soundLevel);
        }
        click.play(1.0f * Constants.soundLevel);
    }
});

soundPButton = new ImageButton(drawableSoundP);
soundPButton.addListener(new ClickListener(){
    @Override
    public void clicked(InputEvent event, float x, float y) {
        if (Constants.soundLevel < 1.0) {
            Constants.soundLevel += 0.1;
            System.out.println(Constants.soundLevel);
        }
        click.play(1.0f * Constants.soundLevel);
    }
});

However, my output is

0.9
0.79999995
0.6999999
0.5999999
0.4999999
0.39999992
0.29999992
0.19999993
0.09999993
-7.301569E-8

Does anyone know why it's like this and not 0.9, 0.8, 0.7, etc.?

0

1 Answer 1

1

Floats and Doubles suffer from precision errors. You should round it to 1 decimal value. From Here.

DecimalFormat oneDigit = new DecimalFormat("#,##0.0");

...

Constants.soundLevel = Double.valueOf(oneDigit.format(Constants.soundLevel));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.