-1

目前我有2双,一个不含税的价格和税率。

价格:9.79(基本11但不含税)税:11%

现在我需要做的是再次获得包含价格的税,所以我这样做:

// Tax exclusive test
double taxRate = 0.11;
double priceWithTax = 11;
double priceWithoutTax = priceWithTax * (1.0 - taxRate);

NSLog(@"priceWithoutTax = %f", priceWithoutTax);

double result = priceWithoutTax * (1 + taxRate);

NSLog(@"Result: %f", result);

但是在执行我的输出时,它是这样的:

priceWithoutTax = 9.790000
Result: 10.866900

预期的输出将再次为 11。如果有人可以提供帮助,那就太好了,我检查了很多关于浮点精度的资源,但我似乎找不到答案。

提前致谢!

更新(Bathsheba 回答后的新代码)

// Tax exclusive test
double taxRate = 0.11;
double priceWithTax = 11;
double priceWithoutTax = priceWithTax * (1.0 - taxRate);

NSLog(@"priceWithoutTax = %f", priceWithoutTax);

double result = priceWithoutTax / (1 - taxRate);

NSLog(@"Result: %f", result);

结果:

priceWithoutTax = 9.790000
Result: 11.000000
4

2 回答 2

3

芭丝谢芭的回答是不正确的。他的结果给了你一致的答案,但你的问题是你试图取一个含税的价格,并计算不含税的那个项目的价格。为此,芭丝谢巴的数学是不正确的。

double result = priceWithoutTax * (1 + taxRate);是计算 priceWithTax 的正确方法。

例如,一件价值 10 美元的衬衫(不含税加 5% 的税)将花费您总计 10.50 美元

double priceWithoutTax = priceWithTax * (1.0 - taxRate);是从 priceWithTax 计算 priceWithoutTax 的错误公式。使用与 10 美元衬衫相同的示例,代入此公式将为您提供priceWithoutTax = $10.50 * (1.0 - 0.05) = $9.975. 你知道这是错误的答案,因为你知道这件衬衫的价格正好是 10 美元(不含税)。

计算 priceWithoutTax 的正确方法:double priceWithoutTax = priceWithTax / (1.0 + taxRate);

再次检查衬衫。priceWithoutTax = $10.50 / (1.0 + 0.05) = $10

于 2013-07-09T19:45:57.140 回答
3

你的数学不正确:你需要double result = priceWithoutTax / (1.0 - taxRate);.

松散地说,浮点精度只能归咎于第 14 位有效数字的错误(对于双精度数)。

于 2013-07-09T12:50:50.920 回答