Error in float value
I am a newbie in JAVA. When I wrote the following code in java it gives me error:
public class FloatTest
public static void main(String args)
It gives me an error saying possible lose of precision. Aren't float value capable of storing values with decimal point?
You need to use double i think, also try to use tags
# float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
# double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
The compiler gives 3.14 the type of double. Assigning a double to a float could give "possible lose of precision".
If you want a float literal append an F: 3.14F
A bit more clarification: when the compiler sees the textual representation of a number with decimal fractions (a dot followed by more digits) it assumes a number of type double. If you want to assign that number to a variable of type float the compiler starts whining because you might lose precision (some fractional digits).
There are two ways to solve this little issue:
1) Tell the compiler you are dealing with float numbers by appending a single 'f' to your number, i.e. 3.14f or
2) use variables of type double instead of type float.
edit: I'm just a slow old sod ... ;-)
Thanks very much for your answers... :)
To the original poster, welcome to the forum, and I'm glad that your question got answered, but I do request that if you cross-post a question you provide links to the other cross-posts. Nobody likes duplicating work that's already been done. Thanks for your cooperation as this question has already been answered in the Sun fora.