对于我的GDX程序,我使用两个按钮创建了一个选项菜单。其中一个增加了音量,其中一个降低了音量。只要单击一个按钮,它就会增加/减少0.1。这是代码:
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);
}
});
但是,我的输出是
0.9
0.79999995
0.6999999
0.5999999
0.4999999
0.39999992
0.29999992
0.19999993
0.09999993
-7.301569E-8
有谁知道为什么会这样,而不是0.9,0.8,0.7等?
答案 0 :(得分:1)
Floats和Doubles遭遇精确错误。你应该将它四舍五入到十进制值。 From Here
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
...
Constants.soundLevel = Double.valueOf(oneDigit.format(Constants.soundLevel));