JC.*_*JC. 97 c# formatting decimal
是否有一个显示格式化程序,它将在c#中输出小数作为这些字符串表示而不进行任何舍入?
// decimal -> string
20 -> 20
20.00 -> 20
20.5 -> 20.5
20.5000 -> 20.5
20.125 -> 20.125
20.12500 -> 20.125
0.000 -> 0
Run Code Online (Sandbox Code Playgroud)
{0.#}将舍入,并且使用某些Trim类型函数将无法使用网格中的绑定数字列.
Tob*_*oby 136
您是否需要显示最大小数位数?(您的示例最多为5).
如果是这样,我认为格式化为"0.#####"会做你想要的.
static void Main(string[] args)
{
var dList = new decimal[] { 20, 20.00m, 20.5m, 20.5000m, 20.125m, 20.12500m, 0.000m };
foreach (var d in dList)
Console.WriteLine(d.ToString("0.#####"));
}
Run Code Online (Sandbox Code Playgroud)
Sch*_*lls 30
我刚学会了如何正确使用G
格式说明符.请参阅MSDN文档.有一点注意说明当没有指定精度时,将为十进制类型保留尾随零.为什么他们会这样做我不知道,但指定我们的精度的最大位数应解决这个问题.因此,对于格式化小数,G29
是最好的选择.
decimal test = 20.5000m;
test.ToString("G"); // outputs 20.5000 like the documentation says it should
test.ToString("G29"); // outputs 20.5 which is exactly what we want
Run Code Online (Sandbox Code Playgroud)
Erw*_*yer 16
这种字符串格式应该是你的日子:"0.#############################".请记住,小数最多可以包含29位有效数字.
例子:
? (1000000.00000000000050000000000m).ToString("0.#############################")
-> 1000000.0000000000005
? (1000000.00000000000050000000001m).ToString("0.#############################")
-> 1000000.0000000000005
? (1000000.0000000000005000000001m).ToString("0.#############################")
-> 1000000.0000000000005000000001
? (9223372036854775807.0000000001m).ToString("0.#############################")
-> 9223372036854775807
? (9223372036854775807.000000001m).ToString("0.#############################")
-> 9223372036854775807.000000001
Run Code Online (Sandbox Code Playgroud)
这是我在上面看到的另一种变化.在我的情况下,我需要保留小数点右侧的所有有效数字,意味着在最高有效数字后丢弃全零.只是觉得分享会很好.我不能保证这个效率,但是当试图实现美学时,你已经非常愚蠢到低效率.
public static string ToTrimmedString(this decimal target)
{
string strValue = target.ToString(); //Get the stock string
//If there is a decimal point present
if (strValue.Contains("."))
{
//Remove all trailing zeros
strValue = strValue.TrimEnd('0');
//If all we are left with is a decimal point
if (strValue.EndsWith(".")) //then remove it
strValue = strValue.TrimEnd('.');
}
return strValue;
}
Run Code Online (Sandbox Code Playgroud)
这就是全部,只是想投入我的两分钱.
另一种解决方案,基于dyslexicanaboko的回答,但独立于当前的文化:
public static string ToTrimmedString(this decimal num)
{
string str = num.ToString();
string decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (str.Contains(decimalSeparator))
{
str = str.TrimEnd('0');
if(str.EndsWith(decimalSeparator))
{
str = str.RemoveFromEnd(1);
}
}
return str;
}
public static string RemoveFromEnd(this string str, int characterCount)
{
return str.Remove(str.Length - characterCount, characterCount);
}
Run Code Online (Sandbox Code Playgroud)