issue with DecimalFormat in java -


this question has answer here:

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 in roundingmode formatting. default, uses roundingmode.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

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -