0

I am new in java. I have a problem with Numeric literal. Here is my problem:

  float rank = 1050.86F;

  System.out.println(rank);

The output is: 1050.86

 double rank1 = 1050.86D;
 double rank2 = 1050.86F;

 System.out.println(rank1);
 System.out.println(rank2);

The output of rank1 is: 1050.86

The output of rank2 is: 1050.8599853515625

My question is:

(i)Why the output of rank1 and rank2 are different? and how I calculate that?

(ii) Why do I need to use L, D, F before semicolon? As we already used keyword double, int, so why we need to use L, D, F on variables?

Please Help me. I am new in programming.

1 Answers1

3

To answer your first question, it has to do with how computers store numbers internally. Computers use floating point to store numbers. Double precision ("double") stores more "information" in each number than floats. There are 64 bits stored for a double, and 32 bits stored for a float. See how 64 is twice the amount of bits as 32? That's why it's called a double!

Both doubles and floats can only store a limited amount of information in their types, though, so they're not perfectly precise and you can expect little inaccuracies like that to happen all the time in programming. It's nothing to worry about, in fact it's very common to run into floating point errors like you describe. There is no solution other than you should use doubles if you want more precise decimal values. Explaining how to deal with floating point error would take a lot of explaining, so I will link one of my favorite explanations of it here.

To answer your second question, if you don't specify, Java will assume you're using a double value (see here), so you have to specify that you want a float instead. This is because most often you will want to use a double (like I said above, it stores more information), so it makes sense that double is default and you have to specify if you want a float instead.

rb612
  • 5,280
  • 3
  • 30
  • 68