假设我有一个BigDecimal,它可以是任意数量的值。如果第十位的值小于3(即12.2,我希望向下舍入为12)。如果第十位的值大于或等于3(即11.3),我希望将第十位的值向上舍入为5 (所以这里的值最终将是11.5)。BigDecimal是否有现有的功能,可以方便地实现这一点。如果不是,还有什么好的方法来达到这个目的呢?
发布于 2016-10-13 09:53:00
您可以创建自己的BigDecimal版本并覆盖round方法,但这只会在使用该方法时有所帮助。对于它自然进行的舍入(当进行正常的数学运算时),那么没有简单的方法来改变它已经提供的舍入行为。如果您查看一下BigDecimal实现,就会发现许多进行舍入的方法都是静态的,因此您无法覆盖它们。
下面是如何重写round方法。
class MyDecimal extends BigDecimal {
public MyDecimal(BigInteger val) {
super(val);
}
@Override
public BigDecimal round(MathContext mc) {
/* implement your rounding algorithm here*/
}
}发布于 2016-10-14 05:42:16
您可以首先使用setScale()将BigDecimal缩放到10位十进制数字。然后,您可以操作unscaledValue()的最后一位数
public class BigDecimalRounder
{
public static BigDecimal roundToNearestHalf(BigDecimal value)
{
// Scale to 10 decimal digits and get the underlying BigInteger:
BigInteger digits = value.setScale(10, BigDecimal.ROUND_HALF_UP).unscaledValue();
// Act upon the last digit of the BigInteger:
BigInteger lastDigit = digits.mod(BigInteger.TEN);
int intDigit = lastDigit.intValue();
BigInteger newDigit;
if (intDigit >= 0 && intDigit <= 2)
newDigit = BigInteger.ZERO; // round down
else if (intDigit >= 3 && intDigit <= 7)
newDigit = BigInteger.valueOf(5); // round to nearest 5
else
newDigit = BigInteger.TEN; // round up
// Assemble a new BigInteger, removing the original last digit and
// adding the new one (either 0, 5 or 10)
BigInteger newValue = digits.subtract(lastDigit).add(newDigit);
//Assemble a new BigDecimal with the modified digits.
return new BigDecimal(newValue, 10);
}
public static void main(String[] args)
{
BigDecimal mainValue = new BigDecimal("1.2399997990");
BigDecimal addend = BigDecimal.ONE.movePointLeft(10);
for (int i = 1; i <= 12; i++)
{
System.out.println("" + mainValue + " --> " + roundToNearestHalf(mainValue));
mainValue = mainValue.add(addend);
}
}
}输出:
1.2399997990 --> 1.2399997990
1.2399997991 --> 1.2399997990
1.2399997992 --> 1.2399997990
1.2399997993 --> 1.2399997995
1.2399997994 --> 1.2399997995
1.2399997995 --> 1.2399997995
1.2399997996 --> 1.2399997995
1.2399997997 --> 1.2399997995
1.2399997998 --> 1.2399998000
1.2399997999 --> 1.2399998000
1.2399998000 --> 1.2399998000
1.2399998001 --> 1.2399998000https://stackoverflow.com/questions/40010823
复制相似问题