Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to decimal parsing C#

Tags:

c#

I am trying to parse or convert a string to decimal in C#.

I need to be able to parse strings like,

$123,345,676.8999 to its equivalent 123345676.90.

I need to have only 2 places after the decimal point and that needs to be suitably rounded.

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.

like image 595
Tendulkar Avatar asked Dec 03 '22 01:12

Tendulkar


2 Answers

Try this:

var val = double.Parse("$123,345,676.8999", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);
val = Math.Round(val, 2);
like image 62
Chandu Avatar answered Dec 24 '22 00:12

Chandu


You can use decimal.TryParse to perform the parsing -- the link has some samples on how the parsing works.

like image 40
Bryan Crosby Avatar answered Dec 24 '22 00:12

Bryan Crosby