Float Range in Java

I am trying to use the following code in Java:

import java.math.*; public class trial { public static void main(String[] args) { // create a BigDecimal object BigDecimal bg; // create a Float object Float f; float f2 = 35912062; bg = new BigDecimal(35912062); // assign the converted value of bg to f f = bg.floatValue(); String str = "Float value of " + bg + " is " + f; bg = new BigDecimal(f); String str2 = "BigDecimal value of " + bg; // print f value System.out.println( str ); System.out.println( str2 ); System.out.println( 35912062f ); System.out.println(f2); } } 

So, the following result I get:

  Float value of 35912062 is 3.5912064E7 BigDecimal value of 35912064 3.5912064E7 3.5912064E7 

Now I believe this is because it extends the range of float, but when I read this: What is the comprehensive range of float and double in Java?

it displays an inclusive range of floats: 3.40282346638528860e + 38

It confused me a lot. Any links giving explanations will help.

EDIT: Let's say I take 25912062 in place of 35912062, the output for 25912062 is 25912062, but for 35912062 the output is 35912064, why is that?

+5
source share
1 answer

Basically, floating point values โ€‹โ€‹are stored as a pair of mantissa and exponent. Mantissa describes the significant digits of a number (consider this a number from 0 to 9.99). The indicator is scale. Your number is represented as mantissa * 2 ^ x.

We are talking about a representation in the binary system that even direct numbers (in decimal), such as 35912062, do to something that may not exactly match the accuracy of the mantissa. In these cases, you get some rounding problems, especially since the float has a limited range for the mantissa.

Executing code using double (instead of float) gives the result 3.5912062E7.

If you really want to know what java (or floating point arithmetic) does of your number, you should do System.out.println(new Bigdecimal(123.456)) and be surprised.

The message here is, if you really need accurate arithmetic, always take BigDecimal. Because there are additional reservations. For example, adding a large double and a small double can cause the small double to be completely rounded. This leads us to the funny:

  for (float f = 35912062f; f < 55912062f; f++) { System.out.println(f); } 

will never stop. Just give it a try.

+3
source

Source: https://habr.com/ru/post/1271325/


All Articles