【发布时间】:2021-01-26 16:43:49
【问题描述】:
我正在制定一项所得税计划,其计算基于 - 申报状态和 - 应税收入
所有部分必须在小数点后正好有两位数。
问题是输出在小数点后显示两个零,而不是预期的数字。
例如:
预期值> 单次申报:42806 美元。50
实际价值> 单次申报:42806 美元。00
到目前为止,这是我的代码:
// Single Status
if (status == 1) {
if (income > 0 && income <= 8350) {
double firstTax = (int)(income * (0.10));
double totalTax = firstTax;
result = "Single Filing: $" + String.format("%.2f",totalTax) + "(Part I: $" + String.format(("%.2f"),firstTax) + ")";
}
else if (income >= 8350 && income <= 33950) {
double firstTax = (int)(8350 * (0.10));
double secondTax = (int)( (income - 8350) * (0.15));
double totalTax = firstTax + secondTax;
result = "Single Filing: $" + String.format("%.2f",totalTax) + "(Part I: $" + String.format(("%.2f"),firstTax) + ", Part II: $" + String.format(("%.2f"),secondTax) + ")";
}
else if (income >= 33950) {
double firstTax = (int)(8350 * (0.10));
double secondTax = (int)( (33950 - 8350) * (0.15));
double thirdTax = (int)((income - 33950) * (0.25));
double totalTax = firstTax + secondTax + thirdTax;
result = "Single Filing: $" + String.format("%.2f",totalTax) + "(Part I: $" + String.format(("%.2f"),firstTax) + ", Part II: $" + String.format(("%.2f"),secondTax) + ", Part III: $" + String.format(("%.2f"),thirdTax) + ")";
}
}
【问题讨论】:
-
一般提示:切勿使用
float或double等原始数据类型进行货币计算。这些数据类型的精度有限,因此不能代表所有十进制数字,因此从长远来看会导致计算错误。请参阅:Is floating point math broken? - 如果该代码应该对人们的真钱进行计算,我强烈建议使用像BigDecimal这样的非原始数据类型。
标签: java database report decimalformat tax