Convert strings to decimal in C #

I am having problems converting a string to decimal values ​​with a decimal key. This is the line of code I have:

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

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

Then, as soon as the parsing happens to a decimal number, I get this value: 77999.

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

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

+3
source share
4 answers

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
}
+6

CultureInfo , .

CultureInfo IFormatProvider

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

It seems that you run this in a culture where '.'is the group separator and the ','decimal separator. To get around this, use the Parse overload, which takes a CultureInfo value:

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

Also check out NumberStylesenum so you don't have to worry about currency signs:

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

This works for me:

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

All Articles