在C#中使用float计算财务价值的问题 [英] Issue with calculating financial values using float in C#
问题描述
我正在阅读一篇有关Float和double的区别的文章.他们给出了一个示例,如下所示:
I was reading an article related to difference between Float and double. and they given an example as below :
假设您有一件$ 100的商品,并给您10%的折扣.您的价格全为美元,因此您可以使用int变量存储价格.这是您得到的:
Say you have a $100 item, and you give a 10% discount. Your prices are all in full dollars, so you use int variables to store prices. Here is what you get:
int fullPrice = 100;
float discount = 0.1F;
Int32 finalPrice = (int)(fullPrice * (1-discount));
Console.WriteLine("The discounted price is ${0}.", finalPrice);
猜猜看:最终价格是89美元,而不是预期的90美元.您的客户会很高兴,但您不会.您给了他们1%的额外折扣.
Guess what: the final price is $89, not the expected $90. Your customers will be happy, but you won't. You've given them an extra 1% discount.
在上面的示例中,他们使用fullPrice * (1-discount)
来计算最终价格.他们为什么使用(1-disocunt)
?应该是fullPrice * discount
.
In above example, to calculate the final price they have used fullPrice * (1-discount)
. why they used (1-disocunt)
? it should be fullPrice * discount
.
所以我的困惑在于计算最终价格的逻辑.为什么thay使用(1-discount)
而不是discount
?
so my confusion is about logic to calculate the final price. why thay used (1-discount)
instead of discount
?
推荐答案
最终价格为89美元,而不是预期的90美元
the final price is $89, not the expected $90
这是因为,当0.1
是float
时,它不完全是0.1
,而是更多.从1
减去它进行数学运算时,得到$89.9999998509884
.强制转换为int
会将结果截断为89
(演示).
That's because when 0.1
is float
, it is not exactly 0.1
, it's a little more. When you subtract it from 1
to do the math, you get $89.9999998509884
. Casting to int
truncates the result to 89
(demo).
您可以通过使用decimal
数据类型进行打折来实现此目的.此类型可以表示0.1而不会造成精度损失(演示).
You can make this work by using decimal
data type for your discount. This type can represent 0.1 without a precision loss (demo).
为什么使用
(1-disocunt)
1
表示100%.折后价为(100%-10%)= 90%
1
represents 100%. The price after discount is (100%-10%)=90%
这篇关于在C#中使用float计算财务价值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!