c# – Converting a variable with replace to decimal

Question:

I have a little doubt, I pass a 0,05 decimal value to a variable A of type string . Once this variable receives this value, it converts from , to dot . , which is 0.05

After I do this replace, I convert the data to type Decimal , my variable B that receives variable A is inteira 5 .

 var openingCostValue = Convert.ToDecimal(model.openingCost.Replace(",", "."));

What I want is to keep the value that was converted in replace.

Answer:

The correct way to do this is an attempt to parse taking into account the culture (there are hacks that will only work by coincidence). If I had more information in the question I could give a more specific example. I'll give you a generic example:

decimal.TryParse("0,05", NumberStyles.Number, new CultureInfo("pt-BR"), out valor)

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

Data and presentation is something different. Depending on what you need, this may not be the solution. I answered what was asked.

Eventually it is possible not to use the try mechanism but you can only do this if you are sure that the conversion will always succeed. If the data comes externally, or from some component that cannot guarantee it, you cannot be sure.

Scroll to Top