variable decimal places in .Net string formatters?

ぐ巨炮叔叔 提交于 2019-11-29 11:18:57

问题


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 ?


回答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)));



回答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);



回答3:


Probably the most efficient approach for formatting a single value:

int decimalPlaces= 2;
double value = Math.PI;
string formatString = String.Format("F{0:D}", decimalPlaces);
value.ToString(formatString);



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



回答5:


Use the custom numeric format string Link

var value = 654.321;
var s = value.ToString("0.##");



回答6:


use

string.Format("{0:F2}", 654.321);

Output will be

654.32



来源:https://stackoverflow.com/questions/7108850/variable-decimal-places-in-net-string-formatters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!