Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (2.6k points)

What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the previous number. This is the standard method of rounding most people expect in most situations.

I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.

I know one method of doing this is to use the String.format method:

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

returns:

0.91239

which is great, however, it always displays numbers with 5 decimal places even if they are not significant:

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

returns:

0.91230

Another method is to use the DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.#####");

df.format(0.912385);

returns:

0.91238

However, as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:

0.912385 -> 0.91239

0.912300 -> 0.9123

What is the best way to achieve this in Java?

1 Answer

0 votes
by (2k points)

You can use setRoundingMode, In this, you need to set the RoundingMode to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

Input:

DecimalFormat df = new DecimalFormat("#.####");

df.setRoundingMode(RoundingMode.CEILING);

for (Number n : Arrays.asList(11, 123.12335, 0.33, 0.2, 2341234.212431334)) {

    Double d = n.doubleValue();

    System.out.println(df.format(d));

}

Output:

11

123.1234

0.33

0.2

2341234.2124

Click here to learn more about setRoundingMode and here for RoundingMode.

Related questions

0 votes
2 answers
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...