Java取整函数ceilfloorroundrint

Java取整函数ceilfloorroundrint,第1张

Java取整函数ceil/floor/round/rint 取整函数方法

学习分享 Math常用取整函数


一 常用的
System.out.println(Math.ceil(5.2));      //向上取整     结果6.0
System.out.println(Math.floor(5.2));     //向下取整     结果5.0
System.out.println(Math.round(5.01));    //四舍五入     结果5

Ceil 向上取整
Floor 向下取整
Round 四舍五入


二、特殊

Rint — 四舍六入,五取(2个接近数之间偶数

System.out.println(Math.rint(1.49));//1
System.out.println(Math.rint(1.5));//2 (2 3)
System.out.println(Math.rint(1.51));//2

System.out.println(Math.rint(2.49));//2
System.out.println(Math.rint(2.5));//2 (2 3)
System.out.println(Math.rint(2.51));//3

System.out.println(Math.rint(3.49));//3
System.out.println(Math.rint(3.5));//4 (3 4)
System.out.println(Math.rint(3.51));//4

取最近的整数,中间数取2个数的偶数

如 1.5 在1与2之间,取偶数2;
如 2.5在2与3之间,取偶数2;
如 3.5在3与4之间,取偶数4;

到这里明白了rint函数使用了


这里提出2个问题

问题一 round 取整,返回是整数,如果保留2位数怎么办?

System.out.println(String.format("%.2f",0.125));

另外一个方法

BigDecimal bigDecimal=new BigDecimal(0.125);
bigDecimal=bigDecimal.setScale(2, RoundingMode.HALF_UP);

问题二 银行家取整法如何实现?
希望网友可以补充哦!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5697813.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存