bigdecimal precision and scale

we might see two way of setting round in BigDecimail:

// 1.
BigDecimal r1  = new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
// 2.
BigDecimal r2 = new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);

r1 is 35.35

r2 is 35.3456

Well, at first glance it seems that r1 differs from r2 in only one thing: the r1 is using RoundingMode through MathContext object, while the r2 is using the RoundingMode through setScale(-) method.

There is big difference.

But when you look at the JavaDocs, you’ll find that the MathContext constructor is accepting not a scale argument but aprecision one:

MathContext(int setPrecision, RoundingMode setRoundingMode)

One important point that is alluded to but not directly addressed is the difference between“precision” and “scale” and how they are used in the two statements. “precision” is the total number of digits in a number (number of significant digits. The precision of 0.000042M is 2. ). “scale” is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s