devxlogo

BigDecimal Numbers and Formatting

BigDecimal Numbers and Formatting

[float]s and [double]s are useful for graphics and possible statistics.However they are not recommended for certain calculations requiring absoluteaccuracy, such as when they involve money . That’s because the results produced by [float]ing point and [double] precision math is sometimes inaccurate due to data representation in the computer. Think in terms of:

 double f = 2.9 - 1.1;System.out.println( f );giving: 1.7999999999999998 instead of 1.8Enter the [BigDecimal] number.....import java.math.*;class BigDecimalTest {  public static void main(String[] args) {    BigDecimal a = new BigDecimal("2.9");    BigDecimal b = new BigDecimal("1.1");    BigDecimal c = a.subtract(b);			// Note the convention.    System.out.println(c);				// An accurate value: 1.800000000 =)  }}

Notice that it prints all the digits? To format it…

 BigDecimal trim(BigDecimal n)		// trim ( (BigDecimal) a) to cut off alltrailing zeros{	try	{      	while (true)		{			n = n.setScale(n.scale()-1);		}	}	catch (ArithmeticException e)	{

// Not “real” error: No more trailing zeroes -> Just exit // setScale() tries to eliminate a non-zero digit -> Out of the loop // Remember exceptions are not recommended for exiting loops, but this seems to be the best way…

 	}	return n;}BigDecimal format(BigDecimal n, int dp)	// Sets [n] to [dp] decimal places{	return n.setScale(dp, BigDecimal.ROUND_HALF_UP);	// Sets scale and roundsup if most significant (cut off) number >= 5}

Examples:

 trim(new BigDecimal("2.320000")) -> 2.32format(new BigDecimal("1.4553"), 2) -> 1.46format(new BigDecimal("87"), 7) -> 87.0000000
See also  Essential Measures for Safeguarding Your Digital Data
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