When rounding to n decimal places in Java,

Asked 2 years ago, Updated 2 years ago, 157 views

When you use String's format, you always round it up if it's more than 5.

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

If this is the case

0.91239

It's rounded up well. For example,

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

In this case, I don't want 0 to come out if it's 0 at the end

0.91230

It goes like this. So I looked up the DecimalFormatter in another way, and this method removes the zero at the end

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

In this case, if you look at the output, it doesn't round up and comes out like 0.91238...

All I want is

0.912385 -> 0.91239
0.912300 -> 0.9123

It's something like this. What should I do?

java rounding digits decimal-number

2022-09-22 22:35

1 Answers

setRunningModeUse this to modify RunningMode. Whether it's rounding, lowering, or lifting, you can set it all up.

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
    Double d = n.doubleValue();
    System.out.println(df.format(d));
}


12
123.1235
0.23
0.1
12341234.2125


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.