format a number with commas and decimals in C# (asp.net MVC3)

前端 未结 11 1134
予麋鹿
予麋鹿 2020-11-29 03:40

I Need to display a number with commas and decimal point.

Eg: Case 1 : Decimal number is 432324 (This does not have commas or decimal Points) Need to display it

11条回答
  •  清酒与你
    2020-11-29 04:37

    I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:

    1234.56 => 1,234.56

    1234 => 1,234

    It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).

    string FormatNumber(T number, int maxDecimals = 4) {
        return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
                             @"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
    }   
    
    void Main(){
        foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
            Console.WriteLine(test + " = " + FormatNumber(test));
    }
    

    Produces:

    123 = 123
    1234 = 1,234
    1234.56 = 1,234.56
    123456.789 = 123,456.789
    1234.56789123 = 1,234.5679
    

提交回复
热议问题