Rint Bankers Rounding Versus Round

Math.round rounds half toward positive infinity while Math.rint rounds half to even, so 2.5 becomes 3 or 2 depending on the function a billing path picks.

JavaData Integrity

Code

snippet
public class Rounder {

    public static void main(String[] args) {
        double[] samples = {2.5, 3.5, -2.5, 2.4, 2.6};

        for (double value : samples) {
            long roundHalfUp = Math.round(value);  // 平局向正无穷取整:-2.5 -> -2
            double rintHalfEven = Math.rint(value); // 平局取最近偶数 (bankers)
            System.out.printf("%5.1f -> round=%d rint=%.0f%n", value, roundHalfUp, rintHalfEven);
        }

        // rint 返回 double,可直接参与后续浮点运算
        double rintSum = Math.rint(2.5) + Math.rint(3.5);
        System.out.println("rint sum: " + rintSum);

        // 金额场景用 BigDecimal 显式声明舍入模式,避免双重含义
        java.math.BigDecimal price = new java.math.BigDecimal("2.5")
                .setScale(0, java.math.RoundingMode.HALF_EVEN);
        System.out.println("bigDecimal HALF_EVEN: " + price);
    }
}

Under the hood

All of the logic lives in the class Rounder and the function main.

Repetition is confined to for (double value : samples) — the rest of the file is straight-line.

What to watch for

  • No registry and no lockfile entry — dependencies are absent by design.

Using it

Signature: public static void main(String[] args)

The demo output is labeled (rint sum:, bigDecimal HALF_EVEN:); each label names the call that printed it.

Key statements

long roundHalfUp = Math.round(value);  // 平局向正无穷取整:-2.5 -> -2
double rintHalfEven = Math.rint(value); // 平局取最近偶数 (bankers)
System.out.printf("%5.1f -> round=%d rint=%.0f%n", value, roundHalfUp, rintHalfEven);
java.math.BigDecimal price = new java.math.BigDecimal("2.5")
        .setScale(0, java.math.RoundingMode.HALF_EVEN);
double rintSum = Math.rint(2.5) + Math.rint(3.5);

Interactive Tools for This Topic

FAQ

What does Rint Bankers Rounding Versus Round print when run?
Run it as a complete program — the output lines carry labels such as `rint sum:`, `bigDecimal HALF_EVEN:`.