Use BigDecimal Instead of Double Data Type

Use BigDecimal Instead of Double Data Type

In certain situations, you need to show the exact decimal values. If you use the double data type, you need to truncate the decimal values. To avoid truncation while obtaining proper decimal values, you can use BigDecimal instead of double.

Here’s the code

public static void main(String arg[]){		   BigDecimal bd = new BigDecimal("0");	   bd = bd.add(new BigDecimal("99.99"));   bd = bd.add(new BigDecimal("1.99"));		   System.out.println("BigDecimal result " + bd);		   double d = 99.99;   d = d + 1.99;		   System.out.println("Double result " + d);}BigDecimal result 101.98Double result 101.97999999999999


Share the Post: