java 四写五入涉及的类。

本文介绍了使用Java进行数值四舍五入的方法,包括利用Math类的round、floor和ceil方法,以及通过BigDecimal类实现更精确的四舍五入操作。同时,还提供了自定义函数NumberUtilities.round()来实现特定间隔值的四舍五入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

1:问题如何把double dou=1234.5678;进行保留两位的四写五入为dou=1234.57

BigDecimal bigDecimal = new BigDecimal(dou,new MathContext(6,RoundingMode.HALF_EVEN));
System.out.println("round ---->"+bigDecimal.doubleValue());

这6指定要显示的长度。

2.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

来源于http://esffor.iteye.com/blog/96075

Math.round(par)实现机制内部调用(long)Math.floor(par+1/2)

public static long round(doublea)
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值