Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 28, 2000

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 absolute accuracy, 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.8

Enter 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 all
trailing 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 rounds
up if most significant (cut off) number >= 5
}
Examples:
 
trim(new BigDecimal("2.320000")) -> 2.32
format(new BigDecimal("1.4553"), 2) -> 1.46
format(new BigDecimal("87"), 7) -> 87.0000000
Jeremy Chen
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date