issue with DecimalFormat in java -
this question has answer here:
- how round number n decimal places in java 28 answers
i facing issue in below code -
int precision = 3; string value1 = "2.0425"; string value2 = "2.1425"; decimalformat dfform = new decimalformat(); dfform.setminimumfractiondigits(precision); dfform.setmaximumfractiondigits(precision); system.out.println(dfform.format(value1)); system.out.println(dfform.format(value2));
output -
2.042
2.143
1st output expected 2.043. can me in this?
from docs decimalformat
:
decimalformat
provides rounding modes defined inroundingmode
formatting. default, usesroundingmode.half_even
.
it sounds need:
dfform.setroundingmode(roundingmode.half_up);
that's after you've fixed code call format
on actual numbers, mind you:
bigdecimal value1 = new bigdecimal("2.0425"); bigdecimal value2 = new bigdecimal("2.1425");
if use double
values, you'll still see 2.042, nearest double 2.0425 2.042499999999999982236431605997495353221893310546875.
Comments
Post a Comment