Java十进制舍入以四舍五入为整数,浮点为" n"个小数点并使用不同的舍入模式
时间:2020-02-23 14:34:26 来源:igfitidea点击:
有时在使用double和float时,我们需要将它们四舍五入到特定的小数点以进行计算。
例如,商店使用上半舍入模式将最终价格舍入到小数点后两位。
在Java 5之前,DecimalFormat类用于四舍五入,但使用它与数字不一致,并且它没有提供很多选项。
因此,Java 5引入了" RoundingMode"枚举,并增强了" BigDecimal"类以使用RoundingMode来获取所需的几乎任何类型的舍入。
将BigDecimal与RoundingMode结合使用时,感觉就像您正在使用小数,并且非常易于使用。
这是显示其用法的示例程序。
package com.theitroad.misc;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class RoundingExample {
public static void main(String[] args) {
double l = 100.34567890;
//similar like RegEx but don't have much options
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(l));
//2 decimal places rounding with half up rounding mode
System.out.println(BigDecimal.valueOf(l).setScale(2, RoundingMode.HALF_UP));
//3 decimal places rounding with ceiling rounding mode
System.out.println(BigDecimal.valueOf(l).setScale(3, RoundingMode.CEILING));
System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.CEILING));
//integer rounding with floor rounding mode
System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.FLOOR));
}
}

