Converting a variable with replace to decimal

0

I am having a small question, I pass a 0,05 decimal value to a A variable of type string . After this variable receives this value, it converts , to point . , which is 0.05

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

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

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

    
asked by anonymous 04.01.2016 / 18:58

2 answers

5

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

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

See working on dotNetFiddle .

Given and presentation is something different. Depending on what you need may be that the solution is not even this one. I answered what was asked.

Eventually it is possible to not 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 some component that can not guarantee this, it is not certain.

    
04.01.2016 / 19:21
0

You should use replace if you want to format the display value for the user. Otherwise just convert direct.

A different case is if this string comes from the user. By default the . parts tab is for decimal and , is for thousands.

Logo Convert.ToDecimal("0.05"); = 0,05 and Convert.ToDecimal("0,05"); = 5.

    
04.01.2016 / 19:14