Reputation: 19607
I have a float to represent the zoom factor on an image.
setZoomPercent( currentZoomPercent - 0.1f );
The trouble I'm having is that the decrementation is giving the following result. How can I avoid this ?
Zoom:100.0
Zoom:99.9
Zoom:99.8
Zoom:99.700005
Zoom:99.600006
Zoom:99.50001
Zoom:99.40001
Zoom:99.30001
Zoom:99.20001
Zoom:99.10001
Zoom:99.000015
Zoom:98.90002
Zoom:98.80002
P.S: I'm guessing it has to do with the binary representation of 0.1 in binary.
Upvotes: 0
Views: 490
Reputation: 136002
You can avoid it by using BigDecimal
BigDecimal d1 = new BigDecimal("100.00");
BigDecimal d2 = new BigDecimal("0.1");
for(int i = 0; i < 100; i++) {
d1 = d1.subtract(d2);
System.out.println(d1);
}
produces
99.90
99.80
99.70
99.60
99.50
99.40
99.30
99.20
...
Upvotes: 4