JAVA数值四舍五入

 Math.ceil求最小的整数但不小于本身.  
  Math.round求本身的四舍五入。  
  Math.floor求最大的整数但不大于本身.  

问题

我要进行四舍五入或取近似值.

解决办法

用 Math.round( ) 进行四舍五入, Math.floor( ) 和 Math.ceil( ) 进行上下近似值。NumberUtilities.round( ) 方法可自定义取值。

讨论

很多情况我们需要得到整数部分而不是带有小数的浮点数。比如计算出结果为 3.9999999 ,期望的结果应该是4.0。

Math.round( ) 方法进行四舍五入计算:

trace(Math.round(204.499)); // 显示: 204

trace(Math.round(401.5)); // 显示: 402

Math.floor( ) 方法去掉小数部分,Math.ceil( ) 方法去掉小数部分后自动加1:

trace(Math.floor(204.99)); // 显示: 204

trace(Math.ceil(401.01)); // 显示: 402

如果我想要把90.337 四舍五入到 90.34,可以这么写:

trace (Math.round(90.337 / .01) * .01); //显示: 9.34

trace (Math.round(92.5 / 5) * 5); // 显示: 95

trace (Math.round(92.5 / 10) * 10); // 显示: 90

更好的办法是用自定义函数NumberUtilities.round( ) ,它需要两个参数:

number :要舍入的数字

roundToInterval :间隔值

NumberUtilities 类在 ascb.util 包中。

imported ascb.util.NumberUtilities导入

trace(NumberUtilities.round(Math.PI)); // Displays: 3

trace(NumberUtilities.round(Math.PI, .01)); // Displays: 3.14

trace(NumberUtilities.round(Math.PI, .0001)); // Displays: 3.1416

trace(NumberUtilities.round(123.456, 1)); // Displays: 123

trace(NumberUtilities.round(123.456, 6)); // Displays: 126

trace(NumberUtilities.round(123.456, .01)); // Displays: 123.46

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值