Given below the test code and its output. When I get float value from number value, precision is lost.. Can anyone tell me why this behaviour and also how to handle this?
public static void main(String[] args)
{
try
{
java.lang.Number numberVal = 676543.21;
float floatVal = numberVal.floatValue();
System.out.println("Number value : " + numberVal);
System.out.println("float value : " + floatVal);
System.out.println("Float.MAX_VALUE : " + Float.MAX_VALUE);
System.out.println("Is floatVal > Float.MAX_VALUE ? " + ( floatVal > Float.MAX_VALUE));
}catch(Exception e)
{
e.printStackTrace();
}
}
output:
Number value : 676543.21
float value : 676543.2
Float.MAX_VALUE : 3.4028235E38
Is floatVal > Float.MAX_VALUE ? false
also why the float value lesser than Float.MAX_VALUE?
I love these. But I’ll make it quick and painless.
Floats and decimals (aka floating points) aren’t kept in the memory precisely either. But I don’t want to get into float accuracy vs precision issues here, i’ll just point you to a link – http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
As far as your other question, lemme put it this way, since floats are stored in scientific notation.
MAX_VALUE is 32 orders of magnitude bigger than your float number. Feel free to take a look at here as well http://steve.hollasch.net/cgindex/coding/ieeefloat.html
I’ve spent a great deal of time comparing and fixing some FP issues a few months ago…
Try to use a small delta when comparing floats.
Maybe this link will help you http://introcs.cs.princeton.edu/java/91float/