variable decimal places in .Net string formatters?

后端 未结 8 1563
感动是毒
感动是毒 2020-12-29 04:49

Fixed decimal places is easy

String.Format(\"{0:F1}\", 654.321);

gives

654.3

How do I feed the number of

8条回答
  •  鱼传尺愫
    2020-12-29 05:28

    I use an interpolated string approach similar to Wolfgang's answer, but a bit more compact and readable (IMHO):

    using System.Globalization;
    using NF = NumberFormatInfo;
    
    ...
    
    decimal size = 123.456789;  
    string unit = "MB";
    int fracDigs = 3;
    
    // Some may consider this example a bit verbose, but you have the text, 
    // value, and format spec in close proximity of each other. Also, I believe 
    // that this inline, natural reading order representation allows for easier 
    // readability/scanning. There is no need to correlate formats, indexes, and
    // params to figure out which values go where in the format string.
    string s = $"size:{size.ToString("N",new NF{NumberDecimalDigits=fracDigs})} {unit}";
    

提交回复
热议问题