= 到-6ren">
gpt4 book ai didi

c# - 在 C# 中比较 2 个价格作为数据类型字符串

转载 作者:行者123 更新时间:2023-11-30 13:36:04 26 4
gpt4 key购买 nike

我想知道如何将 2 个价格作为数据类型字符串进行比较。

例子;

string oldPrice = "£1.99";
string newPrice = "£2.50";

我想比较新价格是否 >= 到旧价格,但我不确定如何将字符串转换为小数/整数。去掉 £ 符号。

有什么想法吗?有关如何解决此问题的提示或提示?

最佳答案

这应该有效:

string oldPrice = "£1.99";

decimal result = decimal.Parse(oldPrice, System.Globalization.NumberStyles.Currency);

将货币存储为double 不是一个好主意,最好改用decimal。十进制类型仅在表示以 10 为基数的数字时更准确(例如,用于货币/财务计算的数字)。一般来说,double 类型将为任意实数提供至少同样高的精度和绝对更快的速度。另请查看 thisthis有关何时何地使用 decimaldouble 的更多信息的链接。

另请查看@Triynko 来自 here 的评论:

Here's why you use Decimal for money: Double's accuracy is only 16 decimal digits, and after just a few arithmetic ops, errors will quickly accumulate large enough to creep into the 15, 14, 13, etc. digits. Rounding to "cents" requires at least one digit of full accuracy after cents digit, but really you should reserve 4 or 5 to insulate from cumulative arithmetic errors, which you CANNOT allow to corrupt the hundredths column you use to round the cents. That leaves you with 16 (total) - 2 (cents) - (4 or 5 error padding) = oh $hit only 7 (or less) reliable integer digits for your money!

关于c# - 在 C# 中比较 2 个价格作为数据类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40300527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com