converting string to decimal in c#

浪尽此生 提交于 2021-02-08 02:03:48

问题


I am having some problems converting string to decimal values with decimal.parse. This is the line of code I have:

fixPrice = decimal.Parse(mItemParts.Groups["price"].Value.Replace("$", "").Replace(" ", "").Replace("usd", ""));     

The value from which I am trying to convert is: '$779.99'

Then once the parsing to decimal happens, I am getting this value: 77999.

I would like to get 779.99 instead of 77999. Thanks in advance, Laziale

Regex included: "@"\[^\""]+?)\""[^~]+?\]+?src=\""(?[^\""]+?)\""[^>]+?title=\""(?[^\""]+?)\""[^~]+?price\"">(?[^\<]+?)\<[^~]+?\(?[^\<]+?)\

回答1:


I would use Decimal.TryParse():

decimal parsedDecimal = 0;
string yourCurrency = "$779.99";
bool didParse = Decimal.TryParse(yourCurrency,
                                 NumberStyles.Currency,
                                 new CultureInfo("en-US"), out parsedDecimal);

if(didParse) {
    // Parse succeeded
}
else {
    // Parse failed
}



回答2:


It appears that you are running this in a culture where '.' is the group separator, and ',' is the decimal separator. To get around that, use the Parse overload that takes a CultureInfo:

fixPrice = decimal.Parse(stringExpression, CultureInfo.InvariantCulture);

Also look into the NumberStyles enum so you don't have to worry about currency signs yourself:

fixPrice = decimal.Parse(stringExpression, NumberStyles.Currency, new CultureInfo("en-US"));



回答3:


Pass a CultureInfo instance of the culture you are parsing from.

CultureInfo inherits from IFormatProvider

edit:

Here is a sample for the conversion

Decimal.Parse(yourValue, NumberStyles.AllowCurrencySymbol |
                         NumberStyles.AllowDecimalPoint   |
                         NumberStyles.AllowThousands,
              CultureInfo.InvariantCulture);



回答4:


This works for me:

string decStr = "$779.99";
CultureInfo ci = new CultureInfo("en-US");
decimal fixPrice = decimal.Parse(decStr, NumberStyles.Currency, ci);


来源:https://stackoverflow.com/questions/10145186/converting-string-to-decimal-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!