Math Round And HALF_UP Diverge

Show that Math.round sends ties toward positive infinity while RoundingMode.HALF_UP rounds away from zero, so -2.5 lands on -2 versus -3.

JavaData Integrity

Code

snippet
import java.math.BigDecimal;
import java.math.RoundingMode;

public class RoundingContract {

    public static void main(String[] args) {
        // Math.round 对 .5 一律向正无穷取整:负数的一半并不“远离零”
        System.out.println("round(2.5)   = " + Math.round(2.5));
        System.out.println("round(-2.5)  = " + Math.round(-2.5));
        System.out.println("round(-2.6)  = " + Math.round(-2.6));

        // 两个“四舍五入”的语义在此 diverge:HALF_UP 是远离零方向,-2.5 舍成 -3,
        // 与 Math.round 相差 1
        System.out.println("HALF_UP -2.5 = "
                + new BigDecimal("-2.5").setScale(0, RoundingMode.HALF_UP));

        // 与 Math.round 同语义的是 CEILING:同样是向正无穷方向取整
        System.out.println("CEILING -2.5 = "
                + new BigDecimal("-2.5").setScale(0, RoundingMode.CEILING));
    }
}

How it works

Math Round And HALF_UP Diverge is built around the class RoundingContract and the function main.

Caveats

  • No external surface: all behavior comes from the standard library.

Where you would put it to use

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

Running the file prints labeled results such as round(2.5) =, round(-2.5) =, round(-2.6) = — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

What does Math Round And HALF_UP Diverge print when run?
Execute the whole file; each printed line is prefixed with a label like `round(2.5) =`, `round(-2.5) =`, `round(-2.6) =`.