Float and BigDecimal precision limits

public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal foo,foo1; foo=BigDecimal.valueOf(3.1); foo1=BigDecimal.valueOf(3.1f); System.out.println(foo); System.out.println(foo1); } 

RESULT:
3.1
3.0999999046325684

Why are they different? I am using JDK1.7.0_03

+4
source share
4 answers

3.1 defines a double , and 3.1f defines a float . What you see is the problem that float has to represent this value (float uses β€œonly” 32-bit and double 64-bit).

If you want to pinpoint 3.1 with BigDecimal , use the String constructor:

 BigDecimal foo = new BigDecimal("3.1"); System.out.println(foo); 

Conclusion:

 3.1 
+4
source

float and double are different types with different precision.

BigDecimal.valueOf (double) can fix the presentation error in double , but not in float

IMHO does not use float unless you have a reason to do so.

0
source

The problem is that for float and double you use 32 and 64 bits, respectively, to represent both the integer and decimal parts of the number. The problem arises when you try to represent a fractional value that does not actually have an exact decimal representation in binary bits.

Take .1, for example, there is no way to accurately represent this in base 2, more than there is a way to accurately represent 1/3 in base 10.

So java uses some tricks so that when you say:

 float f = 3.1; System.out.println(f); 

He prints the correct number. However, when you start doing arithmetic with these values, you get rounding errors.

BigDecimal is accurate because it uses a different view. It internally stores BigInteger (which uses int [] to represent huge numbers). He then uses the precision value to tell how many of these integer digits are after the decimal point.

For example, the value 3.1 will be represented in BigDecimal as 31, precision = 1 For this reason, BigDecimal does not suffer from the same rounding issues as float and double.

However, when you use the float / double value to initialize a BigDecimal, the same rounding error does this in the BigDecimal instance. To do this, it is recommended to use String to construct the value.

0
source

I had a similar problem due to a rookie error that I wanted to split:

 BigDecimal bd = new BigDecimal(float); 

This gave that extra precision that I did not want, and set it to String, fixing it ...

However, I did this:

 BigDecimal bd = new BigDecimal(float); bd.setScale(2, RoundingMode.HALF_UP); 

Beginners mistake. I had to do it.

 bd = bd.setScale(2, RoundingMode.HALF_UP); 
0
source

All Articles