Home > Back-end >  Decimal Format in java not giving appropriate result
Decimal Format in java not giving appropriate result

Time:10-13

I'm currently using Decimal Format to obtain a result with 1 decimal data. The result that i got is acceptable when value is less than 9.94 (considering range from 1 to 10).

For example

Case 1 ---> new DecimalFormat("#.#").format(9.85) ---> 9.8 (Okay not rounding)

Case 2 ---> new DecimalFormat("#.#").format(9.86) ---> 9.9 (Okay)

Case 3 ---> new DecimalFormat("#.#").format(9.95) ---> 10 (Not Okay as rounding)

Case 4 ---> new DecimalFormat("#.#").format(9.96) ---> 10 (Okay)

I have a concern here why case 1 & case 3 not behaving in similar fashion. In case 1 Decimal Format gives data as 9.8 for 9.85 without rounding it but in case 3 the data 9.95 is getting rounded & returns 10.

CodePudding user response:

Javadoc of DecimalFormat indicates that the default rounding mode is RoundingMode.HALF_EVEN, which rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

You can select a different rounding mode if needed.

CodePudding user response:

DecimalFormat provides rounding modes defined in RoundingMode for formatting.

By default, it uses RoundingMode.HALF_EVEN.

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Behaves as for RoundingMode.HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for RoundingMode.HALF_DOWN if it's even.

Note that this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations.

It is sometimes known as "Banker's rounding," and is chiefly used in the USA.

This rounding mode is analogous to the rounding policy used for float and double arithmetic in Java.

You can set rounding mode by:

DecimalFormat decimalFormat = new DecimalFormat("#.#");
decimalFormat.setRoundingMode(RoundingMode.CEILING);

RoundingMode

  • Related