String Format Numbers Thousands 123K, Millions 123M, Billions 123B

后端 未结 3 800
天涯浪人
天涯浪人 2020-11-29 01:39

Is there a way using a string formatter to format Thousands, Millions, Billions to 123K, 123M, 123B without having to change code to divide value by Thousand, Million or Bi

相关标签:
3条回答
  • 2020-11-29 02:27

    There are different ways to achieve this, but for me the easiest and quickest is to use the "," custom specifier

    double value = 1234567890;
    
    // Displays 1,234,567,890   
    Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
    
    // Displays 1,234,568K
    Console.WriteLine(value.ToString("#,##0,K", CultureInfo.InvariantCulture));
    
    // Displays 1,235M
    Console.WriteLine(value.ToString("#,##0,,M", CultureInfo.InvariantCulture));
    
    // Displays 1B
    Console.WriteLine(value.ToString("#,##0,,,B", CultureInfo.InvariantCulture));
    
    0 讨论(0)
  • 2020-11-29 02:38

    You can implement a ICustomFormatter that divides the value by thousand, million or billion, and use it like this:

    var result = string.Format(new MyCustomFormatter(), "{0:MyFormat}", number);
    
    0 讨论(0)
  • 2020-11-29 02:41

    I use this mix of formats in an Extension Method (just add it to your project and enjoy)

    0 讨论(0)
提交回复
热议问题