将所有这些双精度值更改为BigDecimal的最佳方法是什么?我想我开始时没有意识到我应该将BigDecimal用于基于财务的程序。我对Java很陌生,感谢任何反馈。
private static class TaxBracket {
final double minSalary;
final double maxSalary;
final double taxRate;
TaxBracket(double minSalary, double maxSalary, double taxRate) {
this.minSalary = minSalary;
this.maxSalary = maxSalary;
this.taxRate = taxRate;
}
}
private static TaxBracket[] singleFiler;
static {
singleFiler = new TaxBracket[]
{
new TaxBracket(0.0, 9075.0, 0.10), //Index 0 TierOne
new TaxBracket(9076.0, 36900.0, 0.15), //Index 1 TierTwo
new TaxBracket(36901.0, 89350.0, 0.25), //Index 2 TierThree
new TaxBracket(89351.0, 186350.0, 0.28),//Index 3 TierFour
new TaxBracket(186351.0, 405100.0, 0.33),//Index 4 TierFive
new TaxBracket(405101.0, 406750.0, 0.35),//Index 5 TierSix
new TaxBracket(406751.0, Double.MAX_VALUE, 0.396)//Index 6 TierSeven
};
}
private static TaxBracket[] jointFiler;
static {
jointFiler = new TaxBracket[]
{
new TaxBracket(0.0, 18150.0, 0.10), //Index 0 TierOne
new TaxBracket(18151.0, 73800.0, 0.15), //Index 1 TierTow
new TaxBracket(73801.0, 148850.0, 0.25), //Index 2 TierThree
new TaxBracket(148851.0, 226850.0, 0.28),//Index 3 TierFour
new TaxBracket(226851.0, 405100.0, 0.33),//Index 4 TierFive
new TaxBracket(405101.0, 457600.0, 0.35),//Index 5 TierSix
new TaxBracket(457601.0, Double.MAX_VALUE, 0.396)//Index 6 TierSeven
};
}
private static TaxBracket[] hohFiler;
static {
hohFiler = new TaxBracket[]
{
new TaxBracket(0.0, 12950.0, 0.10), //Index 0 TierOne
new TaxBracket(12951.0, 49400.0, 0.15), //Index 1 TierTow
new TaxBracket(49401.0, 127550.0, 0.25), //Index 2 TierThree
new TaxBracket(127551.0, 206600.0, 0.28),//Index 3 TierFour
new TaxBracket(206601.0, 405100.0, 0.33),//Index 4 TierFive
new TaxBracket(405101.0, 432200.0, 0.35),//Index 5 TierSix
new TaxBracket(432201.0, Double.MAX_VALUE, 0.396)//Index 6 TierSeven
};
答案 0 :(得分:1)
你应该:
double
更改为BigDecimal
。new TaxBracket(...)
的参数,例如始终9075.0
到new BigDecimal("9075.0")
。注意引号。如果你没有引用你所获得的价值,那就不会解决任何问题。或者你可以将构造函数参数更改为String
并在构造函数中执行new BigDecimal(...)
,这可能更整洁。
答案 1 :(得分:0)
您可以这样做(如果您想将双值保留为输入):
void changeToBigDecimal(){
BigDecimal minSalaryDec = new BigDecimal(this.minSalary, MathContext.DECIMAL64);
BigDecimal maxSalaryDec = new BigDecimal(this.maxSalary, MathContext.DECIMAL64);
BigDecimal taxRateDec= new BigDecimal(this.taxRate, MathContext.DECIMAL64);
}
在构造函数中设置初始值后调用它。如果你愿意,你也可以把它们变成全局变量而不是本地变量。
答案 2 :(得分:-1)
我建议您将TaxBracket类顶部的3个双变量更改为BigDecimals。在TaxBracket的构造函数中,使用BigDecimal constructor that takes a double
当你完成时,它应该看起来像这样:
private static class TaxBracket {
final BigDecimal minSalary;
final BigDecimal maxSalary;
final BigDecimal taxRate;
TaxBracket(double minSalary, double maxSalary, double taxRate) {
this.minSalary = new BigDecimal(minSalary);
this.maxSalary = new BigDecimal(maxSalary );
this.taxRate = new BigDecimal(taxRate );
}