Java中的round()
函数使用的是四舍五入(Round half up)规则。这意味着当一个数字恰好位于两个可能结果的中间时,它会向最接近的偶数方向舍入。例如:
这种舍入方式有助于减少在多次舍入操作中的误差累积。
以下是一些示例:
System.out.println(Math.round(11.5)); // 输出 12
System.out.println(Math.round(10.5)); // 输出 11
System.out.println(Math.round(10.4)); // 输出 10
System.out.println(Math.round(-11.5)); // 输出 -12
System.out.println(Math.round(-10.5)); // 输出 -11
System.out.println(Math.round(-10.4)); // 输出 -10
需要注意的是,round()
函数返回的是一个长整型(long
)值,如果你需要得到一个浮点数结果,可以使用Math.rint()
函数。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Java中round函数如何进行四舍五入