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 they are different result? I am using JDK1.7.0_03
3.1
defines a double
while 3.1f
defines a float
. What you see is the problem the float
has of representing that value (float uses "only" 32-bits and double 64-bits).
If you want to define a 3.1
exactly using BigDecimal
use the String
constructor:
BigDecimal foo = new BigDecimal("3.1");
System.out.println(foo);
Output:
3.1