蓝桥杯JAVA-番外篇之四舍五入(JAVA实现)

本文最后更新于:March 16, 2022 pm

积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里,不积小流无以成江海。齐骥一跃,不能十步,驽马十驾,功不在舍。面对悬崖峭壁,一百年也看不出一条裂缝来,但用斧凿,能进一寸进一寸,能进一尺进一尺,不断积累,飞跃必来,突破随之。

目录

String

1
2
System.out.println(String.format("%.0f",7.0/2)); //4
System.out.println(String.format("%.0f",7.0/3)); //2

Math

1
2
System.out.println(Math.round(7.0/2)); //4
System.out.println(Math.round(7.0/3)); //2

BigDecimal

1
2
3
4
5
6
7
BigDecimal bd1 = new BigDecimal(7.0/2);
BigDecimal bigDecimal1 = bd1.setScale(0, RoundingMode.HALF_UP); //保留0位,方式为常规四舍五入
System.out.println(bigDecimal1); //4

BigDecimal bd2 = new BigDecimal(7.0/3);
BigDecimal bigDecimal2 = bd2.setScale(0, RoundingMode.HALF_UP);
System.out.println(bigDecimal2); //2