0

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?

Dawson Smith
  • 473
  • 1
  • 6
  • 15
  • 3
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – OH GOD SPIDERS Aug 09 '21 at 12:57
  • @OHGODSPIDERS should doubles be used at all times instead of float? – Dawson Smith Aug 09 '21 at 12:59
  • There are times to use floats. If you don't have a reason not to then you should probably stick to doubles. – matt Aug 09 '21 at 13:02
  • The point is that both double and float have limited precision and cannot hold all possible decimal values (There are an infinite number of decimal numbers after all). When using those data types you just need to be aware of this limited precision. And when you need to do precise calculation (like writing a program that does calculations with real peoples money) you should use a data type that does not have this precision problem like BigDecimal. – OH GOD SPIDERS Aug 09 '21 at 13:14

1 Answers1

1

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().