JAVA数值四舍五入

来源:互联网 发布:怪兽汉化 知乎 编辑:程序博客网 时间:2024/05/16 23:44

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​

java学习资料直播公开课请加老师Q578024144

原创粉丝点击