Java float unlogical output
问题描述:
对于我的GDX程序,我制作了一个带有两个按钮的选项菜单。其中一个增加了音量,其中一个降低了音量。每按一次按钮,它就会增加/减少0.1。下面是代码:Java float unlogical output
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,等等?
答
浮球和双打遭受精度错误。你应该将它舍入到1个十进制值。 From Here。
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
...
Constants.soundLevel = Double.valueOf(oneDigit.format(Constants.soundLevel));