devxlogo

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
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist