variable decimal places in .Net string formatters?

12,366

Solution 1

Use NumberFormatInfo:

Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 2 }, "{0:F}", new decimal(1234.567)));
Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 7 }, "{0:F}", new decimal(1234.5)));

Solution 2

The string to format doesn't have to be a constant.

int numberOfDecimalPlaces = 2;
string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}");
String.Format(formatString, 654.321);

Solution 3

Another option is using interpolated strings like this:

int prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);

Still a mess, but yet more convenient IMHO. Notice that string interpolation replaces double braces, like {{, with a single brace.

Solution 4

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}";

Solution 5

I used two interpolated strings (a variant of Michael's answer):

double temperatureValue = 23.456;
int numberOfDecimalPlaces = 2;

string temperature = $"{temperatureValue.ToString($"F{numberOfDecimalPlaces}")} \u00B0C";
Share:
12,366

Related videos on Youtube

GazTheDestroyer
Author by

GazTheDestroyer

Updated on June 05, 2022

Comments

  • GazTheDestroyer
    GazTheDestroyer almost 2 years

    Fixed decimal places is easy

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

    gives

    654.3
    

    How do I feed the number of decimal places in as a parameter like you can in C? So

    String.Format("{0:F?}", 654.321, 2);
    

    gives

    654.32
    

    I can't find what should replace the ?

  • GazTheDestroyer
    GazTheDestroyer over 12 years
    Urgh! I thought this might be the answer. An extra string concat for every format seems horrible, but it's either that or write my own formatter I guess. Many thanks.
  • GazTheDestroyer
    GazTheDestroyer over 6 years
    Thanks! Just learned something I didn't know.You might be better off using NumberFormatInfo.CurrentInfo.Clone() to preserve the rest of the current cultureInfo.