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.?

Daahrien
  • 10,190
  • 6
  • 39
  • 71
JasperMW
  • 465
  • 3
  • 7
  • 22

1 Answers1

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));
Daahrien
  • 10,190
  • 6
  • 39
  • 71