Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to decimal

Tags:

c#

In C#, I'm trying to convert a string to decimal.

For example, the string is "(USD 92.90)"

How would you parse this out as a decimal with Decimal.Parse fcn.

like image 671
LB. Avatar asked Oct 28 '09 12:10

LB.


People also ask

How do you convert a string to a numerical value?

The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.

How do you convert an empty string to a decimal?

It's not possible to convert an empty string to a number (decimal or not). You can test for an empty string before trying the conversion or use decimal. TryParse() - I think that was available in 1.1.

How do you convert string to decimal in Python?

literal_eval() function to convert the hexadecimal string to decimal string. convertion = literal_eval(testing_string) # At last, print result. print ("The converted hexadecimal string into decimal string is: " + str(convertion))

Can we convert decimal to string in C#?

ToString() is a method in C# that is called on decimal values. It converts a numeric value that is a decimal to a string.


2 Answers

I'm going on the assumption here that the string you're trying to parse is an actual currency value.

CultureInfo c = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
c.NumberFormat.CurrencyNegativePattern = 14; // From MSDN -- no enum values for this
c.NumberFormat.CurrencySymbol = "USD";

decimal d = Decimal.Parse("(USD 92.90)", NumberStyles.Currency, c);
like image 92
Jon Seigel Avatar answered Oct 05 '22 23:10

Jon Seigel


You could start off with a reg-exp to extract the number part and then use Decimal.TryParse to parse the sub-string.

like image 39
Skizz Avatar answered Oct 05 '22 23:10

Skizz