计算个人所得税,需要四舍五入保留2位小数
csdn有很多篇文章讲述了四舍五入保留2位小数的多种方法,经过实测,下面这种方法最准确
通过对多个边缘值的测试,均无问题
public class MathUtil {
private MathUtil() {
}
private static String formatDoubleLeafTwo(double d) {
return String.format("%.2f", d);
}
public static void main(String[] args) {
String v = MathUtil.formatDoubleLeafTwo(1.0);
String v1 = MathUtil.formatDoubleLeafTwo(1.04);
String v2 = MathUtil.formatDoubleLeafTwo(1.044);
String v3 = MathUtil.formatDoubleLeafTwo(1.0445);
String v4 = MathUtil.formatDoubleLeafTwo(1.045);
String v5 = MathUtil.formatDoubleLeafTwo(1.0454);
String v6 = MathUtil.formatDoubleLeafTwo(1.0455);
System.out.println(v);
System.out.println(v1);
System.out.println(v2);
System.out.println(v3);
System.out.println(v4);
System.out.println(v5);
System.out.println(v6);
}
}
测试结果
1.00
1.04
1.04
1.04
1.05
1.05
1.05
double数据类型就是不支持.00这样的数据结构
但是金融行业又要保留2位小数,所以这样的结果使用String保存
通过学习,得知float和double尤其不适合用于货币计算
使用BigDecimal,int,long来进行货币计算