Avoid Round-off error in large & Small numbers using BigDecimal Class in Java

                   
There are two types of primitive data types used for floating point representation in java called double & float.float is a 32 bit IEEE 754 single precision Floating Point Number & double is a 64 bit IEEE 754 double precision Floating Point Number.So that double has 2x more precision then float.

double d1=.3; double d2=.2;
double d3=d1-d2;
System.out.println(d3);//IEEE754 Result is 0.09999999999999998
But there is a round-ff error in IEEE745 floating point representation in double.So when these data apply to large scale project it will possible to fail(GPS Systems,Banking Systems,Radar System,Air traffic controlling systems etc.)

So avoid that drawback java introduce Class called BigDecimal.Big decimal avoid this problem(But it consumes more space & time complexity than decimal.)
//using as String 
BigDecimal b1 = new BigDecimal(".3");
BigDecimal b2 = new BigDecimal(".2");
BigDecimal b3 = b1.subtract(b2);
System.out.println(b3);


//But file you realy want to use decimal you can use this method
BigDecimal b4 = BigDecimal.valueOf(0.3);
BigDecimal b5 = BigDecimal.valueOf(0.2);
BigDecimal b6 = b4.subtract(b5);
System.out.println(b6.toPlainString());

Comments

Popular posts from this blog

Hibernate-2

Serialization Using java