I will introduce the default behavior when rounding the decimal point using java.text.NumberFormat
and how to change the default behavior.
$ java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
You can round the decimal point by specifying 0
in the setMaximumFractionDigits
method of NumberFormat
.
package com.example;
import java.text.NumberFormat;
import org.junit.Test;
public class NumberFormatTests {
@Test
public void testForDefault() {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(0); //Set the maximum number of decimal places to 0
System.out.println(numberFormat.format(98.5));
System.out.println(numberFormat.format(99.5));
}
}
When I run this code ...
98
100
Will be. Oh? ?? ?? Maybe some people thought that. Intuitively ...
98
99
Or
99
100
I'm hoping that it will be ...
And ... This behavior is managed by NumberFormat
[RoundingMode
](https://docs.oracle.com/javase/jp/8/docs/api/java/math/RoundingMode This is because the default value of .html) is HALF_EVEN
.
Looking at the JavaDoc of HALF_EVEN
, it is a rounding mode that rounds to the" closest number "(however, if the numbers on both sides are equidistant, it is rounded to the even side). Therefore, "98.5" was rounded to "98" (even number) instead of "99" (odd number), and "99.5" was rounded to "100" (even number) instead of "99" (odd number).
Rounding Mode
The RoundingMode
of NumberFormat
can be changed with the setRoundingMode
method.
@Test
public void testForRoundingModeIsDown() {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(0);
numberFormat.setRoundingMode(RoundingMode.DOWN); //Change Rounding Mode
System.out.println(numberFormat.format(98.5));
System.out.println(numberFormat.format(99.5));
}
When I run this code ...
98
99
Will be.
It feels like. I wasn't aware of the fact that the default behavior is HALF_EVEN
, but I learned: sweat_smile: By the way ... I wrote this entry ... Thymeleaf Issue (gh-" 581). If you use Thymeleaf for rounding, you may get unexpected results (at a glance, there was no way to change the RoundingMode
).
Recommended Posts