Round an invoice tie in cents in Java
Construct decimal amounts from text to preserve their stated value. HALF_EVEN chooses the even last digit when two rounded totals are equally close.
A simple example
Round ties to even
- Start with 1.25 at one decimal place
- Do this Round ties to even
- Result 1.2
Apply it to a real problem
- Start with Amounts 12.345 and 12.355
- Do this Round both to cents, ties to even
- Result 12.34 and 12.36
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) throws Exception {
for (String amount : new String[]{"12.345", "12.355"}) {
var total = new BigDecimal(amount).setScale(2, RoundingMode.HALF_EVEN);
System.out.println(total.toPlainString());
}
}
}
12.34 12.36