简体   繁体   English

字符串到十进制解析 C#

[英]String to decimal parsing C#

I am trying to parse or convert a string to decimal in C#.我正在尝试在 C# 中解析或转换字符串为十进制。

I need to be able to parse strings like,我需要能够解析像这样的字符串,

$123,345,676.8999 to its equivalent 123345676.90. 123,345,676.8999 美元相当于 123345676.90。

I need to have only 2 places after the decimal point and that needs to be suitably rounded.我只需要小数点后 2 位,并且需要适当四舍五入。

Can you guys please suggest a way to do the above?你们能建议一种方法来做上面的事情吗? Basically, any string in the form of currency (with $,pound symbol etc).基本上,任何货币形式的字符串(带有 $、英镑符号等)。 I should be able to parse it and convert it to decimal.我应该能够解析它并将其转换为十进制。

Try this:尝试这个:

var val = double.Parse("$123,345,676.8999", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);
val = Math.Round(val, 2);

您可以使用decimal.TryParse来执行解析——链接中有一些关于解析如何工作的示例。

非常简单的答案:使用Decimal.Parse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM