Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to decimal in c#

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\"">(?[^\<]+?)\<[^~]+?\(?[^\<]+?)\

like image 987
Laziale Avatar asked Oct 13 '25 04:10

Laziale


2 Answers

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
}
like image 84
James Hill Avatar answered Oct 14 '25 20:10

James Hill


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"));
like image 30
phoog Avatar answered Oct 14 '25 20:10

phoog