目录Math.round()的用法使用细节可以看例题代码验证验证结论总结Math.round()的用法遇到了关于Math.round()的用法的基础题,发现自己还不是太熟悉,所以来总结一下。
Java中的Math.round()方法是将浮点型进行“四舍五入”转换为int类型的一个方法。
使用细节可以看例题
小数点后第一位等于五时:
System.out.println(Math.round(-11.5)); -> 输出为 -11 System.out.println(Math.round(11.5)); -> 输出为 12
小数点后第一位小于五时:
System.out.println(Math.round(-11.41)); -> 输出为 -11 System.out.println(Math.round(11.41)); -> 输出为 11
小数点后第一位大于五时:
System.out.println(Math.round(-11.58)); -> 输出为 -12 System.out.println(Math.round(11.58)); -> 输出为 12代码验证public class main {public static void main(String[] args) {
System.out.println(Math.round(-11.5));System.out.println(Math.round(11.5));
System.out.println(Math.round(-11.41));System.out.println(Math.round(11.41));
System.out.println(Math.round(-11.58));System.out.println(Math.round(11.58));}}
结果图:
一句话结论:
将括号内的数 + 0.5 向下取整即为输出。
验证结论
小数点后第一位等于五时:
System.out.println(Math.round(-11.5)); -> -11.5 + 0.5 = -11 向下取整输出为 -11 System.out.println(Math.round(11.5)); -> 11.5 + 0.5 = 12 向下取整输出为 12
小数点后第一位小于五时:
System.out.println(Math.round(-11.41)); -> -11.41 + 0.5 = -10.91 向下取整输出为 -11 System.out.println(Math.round(11.41)); -> 11.41 + 0.5 = 11.91 向下取整输出为 11
小数点后第一位大于五时:
System.out.println(Math.round(-11.58)); -> -11.58 + 0.5 = -11.08 向下取整输出为 -12 System.out.println(Math.round(11.58)); -> 11.58 + 0.5 = 12.05 向下取整输出为 12总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:Java Math.round(),Math.ceil(),Math.floor()的区别详解详解Java中Math.round()的取整规则JavaScipt中的Math.ceil() 、Math.floor() 、Math.round() 三个函数的理解
