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

  1. Start with 1.25 at one decimal place
  2. Do this Round ties to even
  3. Result 1.2
The nearest tenths are 1.2 and 1.3. The even retained digit is 2.

Apply it to a real problem

  1. Start with Amounts 12.345 and 12.355
  2. Do this Round both to cents, ties to even
  3. Result 12.34 and 12.36
The retained hundredths digit determines the direction at each exact tie.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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());
        }
    }
}
Output
12.34
12.36

Official Java documentation