Best way to convert string to decimal separator “.” and “,” insensitive way?

前端 未结 7 1166
北海茫月
北海茫月 2020-12-15 06:05

Application deals with strings that represent decimals that come from different cultures. For example \"1.1 and \"1,1\" is the same value.

I played with Deci

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 06:29

    I found another way to do it. It looks odd but it works fine for me.

    So if you don't know culture of the target system and you don't know which value you will get like 12.33 or 12,33 you can do following

    string amount = "12.33";
    // or i.e. string amount = "12,33";
    
    var c = System.Threading.Thread.CurrentThread.CurrentCulture;
    var s = c.NumberFormat.CurrencyDecimalSeparator;
    
    amount = amount.Replace(",", s);
    amount = amount.Replace(".", s);
    
    decimal transactionAmount = Convert.ToDecimal(amount); 
    

提交回复
热议问题