Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有小数点后1到2位的.Net格式字符串?_.net_Format String - Fatal编程技术网

是否有小数点后1到2位的.Net格式字符串?

是否有小数点后1到2位的.Net格式字符串?,.net,format-string,.net,Format String,我要求将给定数字的格式设置为至少1位小数,最多2位小数,如下所示: 4 -> 4.0 4.1 -> 4.1 4.25 -> 4.25 4.3333 -> 4.33 4.5 -> 4.5 5 -> 5.0 是否有一个FormatString可以传递此信息 例如: MyDecimal.ToString("[something here]") 是的,您可以有条件地在#格式占位符中包含第二个小数位 MyDecimal.ToStr

我要求将给定数字的格式设置为至少1位小数,最多2位小数,如下所示:

4      -> 4.0
4.1    -> 4.1
4.25   -> 4.25
4.3333 -> 4.33
4.5    -> 4.5
5      -> 5.0
是否有一个FormatString可以传递此信息

例如:

MyDecimal.ToString("[something here]")

是的,您可以有条件地在
#
格式占位符中包含第二个小数位

MyDecimal.ToString("0.0#")

可能是这样的:

myDecimal.ToString("#.0#");
至少,根据您给出的示例,hat'd work.

字符串
“0.0”
应该可以做到这一点。

在C中考虑它;就像下面一样

//max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

或者合并Anthony和Rahul的答案:

string.Format("{0:0.0#}", someNumber);
e、 g:

string formatStr=“{0:0.0#}”;
var输出=新的StringBuilder();
var输入=新列表{4,4.1,4.25,4.3333,4.5,5};
foreach(输入中的var num){
output.AppendLine(num+“->”+string.Format(formatStr,num));
}
/*输出
4 -> 4.0
4.1 -> 4.1
4.25 -> 4.25
4.3333 -> 4.33
4.5 -> 4.5
5 -> 5.0
*/
string formatStr = "{0:0.0#}";

var output = new StringBuilder();

var input = new List<double> { 4, 4.1, 4.25, 4.3333, 4.5, 5 };

foreach ( var num in input ) {
    output.AppendLine(num + " -> " + string.Format(formatStr, num));
}

/* output
4 -> 4.0
4.1 -> 4.1
4.25 -> 4.25
4.3333 -> 4.33
4.5 -> 4.5
5 -> 5.0
*/