Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.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
C# 如何使用.ToString()指定十进制类型的位数_C# - Fatal编程技术网

C# 如何使用.ToString()指定十进制类型的位数

C# 如何使用.ToString()指定十进制类型的位数,c#,C#,我想指定在将值从十进制转换为字符串时需要6位数字。我有以下代码 decimal bound = (decimal) field.MaxVal; //trait.MaxVal is a Nullable decimal... // my debugger shows that bound contains the value 20.0000000000 int numDigits = 6; string num = numDigits.ToString(); string output = bo

我想指定在将值从十进制转换为字符串时需要6位数字。我有以下代码

decimal bound = (decimal) field.MaxVal; //trait.MaxVal is a Nullable decimal...
// my debugger shows that bound contains the value 20.0000000000
int numDigits = 6;
string num = numDigits.ToString();

string output = bound.ToString("G" + num);
// output is '20' i expected '20.0000'
return output;
有没有关于我该怎么做的想法

我专注于在字符串中总共获得6个数字,而不是小数点后4位

注意:绑定的整数部分可能多于或少于2位。

string output = bound.ToString("F" + num);


F代表定点。

这有帮助,但不幸的是,这不是我需要的,我想知道是否可以指定数字的位数。例如,20.0000,且numDigits=4应给出20.00。@Kikanye,如果整数部分大于6位,您能否澄清预期的行为?你想要像“F”+Math.Max(num-Math.Floor(Math.Log10(n)+1),0)这样的东西吗@HereticMonkey不一定,我想知道我是否可以指定数字中我想要的位数,例如,对于20.0000,numDigits=4,我应该得到20.00看起来更像或那样。