How to round a number to n decimal places in Java -


what method convert double string rounds using half-up method - i.e. if decimal rounded 5, rounds previous number. standard method of rounding people expect in situations.

i significant digits displayed - i.e. there should not trailing zeroes.

i know 1 method of doing use string.format method:

string.format("%.5g%n", 0.912385); 

returns:

0.91239 

which great, displays numbers 5 decimal places if not significant:

string.format("%.5g%n", 0.912300); 

returns:

0.91230 

another method use decimalformatter:

decimalformat df = new decimalformat("#.#####"); df.format(0.912385); 

returns:

0.91238 

however can see uses half-even rounding. round down if previous digit even. i'd this:

0.912385 -> 0.91239 0.912300 -> 0.9123 

what best way achieve in java?

use setroundingmode, set roundingmode explicitly handle issue half-even round, use format pattern required output.

example:

decimalformat df = new decimalformat("#.####"); df.setroundingmode(roundingmode.ceiling); (number n : arrays.aslist(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {     double d = n.doublevalue();     system.out.println(df.format(d)); } 

gives output:

12 123.1235 0.23 0.1 2341234.2125 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -