Use Math.round not (int) - I never claimed to be perfect!
Well this post will show my ignorance towards floating point math. So my new Android Application, which I hope to put up on the Market soon, is a shopping list which allows you to track how much you’ve spent as your are shopping. This obviously deals with the price of the products you are purchasing so I expect the user to enter floating point values, but I convert to integers to make math functions go faster.
To convert from float to integer I was using the following code (actually String -> float -> integer).
String sPrice = txtView.getText().toString(); float fPrice = Float.parseFloat( sPrice ); priceInt = (int)( fPrice * 100 );
Well it just so happens that there are some float values that don’t behave quite as expected.
1.26 * 100 = 126.0
Good
3.36 * 100 = 336.0
Cool
2.36 * 100 = 235.99998
Oops.
Well, since I’m not an expert with floats, I didn’t know that this is expected (I should have looked harder), so I filed a bug with the Android issue tracker and promptly got two emails back. The first stating,
Please refer to the following article to understand why it is so. This is not a bug.
http://en.wikipedia.org/wiki/
and the second,
Note also this behavior is common to other Java implementations. Save this as Blah.java:
public class Blah {
public static void main(String[] args) {
float f, g;
f = 2.36f;
g = 100.0f;
System.out.println(f + ” * ” + g + ” = ” + f*g);
}
}
Compile and execute on your desktop VM:
% javac Blah.java && java Blah
2.36 * 100.0 = 235.99998
You can use Math.round() instead of an integer truncation to get the result you were
expecting.
Oops on me…again, I should have done some more investigating. So now my code reads like the following and all is good (and I’ve learned my one thing for the day, and hopefully you won’t make the same mistake!)
String sPrice = txtView.getText().toString(); float fPrice = Float.parseFloat( sPrice ); priceInt = Math.round( fPrice * 100 );

January 28th, 2009 at 6:07 am
Anyone that has been involved in financial applications will tell you that it is very bad practice to perform money calculations with floating point values. Use long ints to perform your calculations and just print it accordingly, that is fixed point math. Do not use floating point values!
January 28th, 2009 at 10:44 am
“2.26 * 100 = 235.99998″ really threw me for a loop…I’m assuming that first number is supposed to be 2.36?
Also, is f*g some sort of censored swear word?
Anyway, this is a good reminder as something we don’t always think of but can make a big difference…
January 28th, 2009 at 12:17 pm
Thanks Jamie, fix made to post for the incorrect value of 2.26.
Tasos, I’m performing the conversion so I can take a currency value that the user has entered via an EditText view widget and convert it to an integer. I’m only doing addition and subtraction and I believe that an integer is what I want to use. Am I correct??