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
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job