Hey all, I am a total newbie developing an android application, I’ve been reading ‘Sams Teach Yourself Java in 24 hours’ and it’s a great book. But I have been stuck on a bit where I get the value of a decimal number only editTexts and use java maths to work out my end value.
- Is there a way to have an editText input straight to a float or double variable rather than to a string and then from a string to a double?
- Are there any real issues with converting between a string and a double or float or will the values remain the same and not be polluted.
- Differences / pros and cons of using a doble as opposed to a float.
- Best way to input a fraction value from the user?
Thanks for any help. Have a good day.
No. You could write your own subclass that makes it seem like that is what’s happening, but at some point somewhere in the chain you have to do a conversion from character/text data to numerical data.
Yes. Primitive floating-point types use IEEE-754 to encode decimal numbers in binary. The encoding provides very good precision, but it is not exact/cannot exactly represent many possible numbers. So if you parse from a string to a primitive floating-point type, and then back to string again, you may get something that is different from your input string.
A double uses twice as many bits to encode the number as a float, and thus is able to maintain a greater degree of precision. It will not, however, remove the issues discussed in #2. If you want to remove those issues, consider using something like
BigDecimalto represent your numbers instead of primitive types likefloatordouble.Read the whole thing as a string,
split()it on the ‘/’ character, and then store each part as an integer (orBigInteger). If you need to display it as a decimal, useBigDecimalto perform the division.