Search code examples
javacasting

Strange output when float value is assigned to a double in JAVA. Getting weird decimals


I'm facing issues understanding typecasting in the case of floats and doubles

float a = 9.8f; 
double b = g; 
double c = 9.8; 
System.out.println(b); 
System.out.println(c);

Output -

9.800000190734863 
9.8

Why is there extra stuff present in the case of b? From where do the extra decimals come from?


Solution

  • You're moving from a smaller data type to a larger one through an implicit data type conversion and this is just the JVM trying to provide a rounding to the closest value it can represent in a double from this float. I would look at Chapter 2. The Structure of the Java Virtual Machine on Oracle's website. I think what OH GOD SPIDERS was getting, for your example here, was to use something like BigDecimal.valueOf((long)(a*100),2).doubleValue().