Convert string value to decimal with thousand separator?

前端 未结 4 1632
慢半拍i
慢半拍i 2021-01-23 17:42

This might be a very simple question. Suppose text box show value 10,000.12 when user edits data by mistake he remove first two numbers like ,000.12 and using this textbox in t

相关标签:
4条回答
  • 2021-01-23 18:26

    This is pretty messed up and I am not sure if all of you strings will look the same, but in case they do this might do the trick:

    string str = ",0,100.12";
    decimal number;
    bool converted = decimal.TryParse(str.Substring(str.LastIndexOf(",") + 1), out number);
    

    The variable converted will tell you whether or not your string was converted and you will not an exception.

    Good luck!

    0 讨论(0)
  • 2021-01-23 18:28
    string a = "100.12";
    decimal b = Convert.ToDecimal(a);
    
    0 讨论(0)
  • 2021-01-23 18:29
    string str = ",0,100.12;";
    var newstr = Regex.Replace(str,@"[^\d\.]+","");
    decimal d = decimal.Parse(newstr, CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2021-01-23 18:36

    If I understood the question, you want to remove all characters that would prevent the parse routine from failing.

    string str = ",0,100.12";
    
    var modified = new StringBuilder();
    foreach (char c in str)
    {
        if (Char.IsDigit(c) || c == '.')
            modified.Append(c);
    }
    
    decimal number= decimal.Parse(modified.ToString());
    
    0 讨论(0)
提交回复
热议问题