Java四舍五入

短命女 2022-07-27 14:49 333阅读 0赞

Java有四舍五入函数—Math.round,通过一个例子看看他的用法:

  1. package math;
  2. public class MathRoundTest {
  3. /**
  4. * Math类中提供了三个与取整有关的方法:ceil,floor,round,
  5. * 这些方法的作用于它们的英文名称的含义相对应,例如:ceil的英文意义是天花板,该方法就表示向上取整,
  6. * Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11;floor的英文是地板,
  7. * 该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12;
  8. * 最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,
  9. * 所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.Math.round( )符合这样的规律:
  10. * 小数点后大于5全部加,等于5正数加,小于5全不加。
  11. */
  12. public static void main(String[] args) {
  13. System.out.println(“小数点后第一位=5”);
  14. System.out.println(“正数:Math.round(11.5)=” + Math.round(11.5));
  15. System.out.println(“负数:Math.round(-11.5)=” + Math.round(-11.5));
  16. System.out.println();
  17. System.out.println(“小数点后第一位<5”);
  18. System.out.println(“正数:Math.round(11.46)=” + Math.round(11.46));
  19. System.out.println(“负数:Math.round(-11.46)=” + Math.round(-11.46));
  20. System.out.println();
  21. System.out.println(“小数点后第一位>5”);
  22. System.out.println(“正数:Math.round(11.68)=” + Math.round(11.68));
  23. System.out.println(“负数:Math.round(-11.68)=” + Math.round(-11.68));
  24. /**
  25. * 运行结果:
  26. 1、小数点后第一位=5
  27. 2、正数:Math.round(11.5)=12
  28. 3、负数:Math.round(-11.5)=-11
  29. 4、
  30. 5、小数点后第一位<5
  31. 6、正数:Math.round(11.46)=11
  32. 7、负数:Math.round(-11.46)=-11
  33. 8、
  34. 9、小数点后第一位>5
  35. 10、正数:Math.round(11.68)=12
  36. 11、负数:Math.round(-11.68)=-12
  37. */
  38. /**
  39. * 1、参数的小数点后第一位<5,运算结果为参数整数部分。
  40. 2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
  41. 3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。
  42. */
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读