如何用固定位数格式化浮点值? [英] How to format floating point value with fix number of digits?
问题描述
在C#中是否可以用double.ToString格式化双精度值,而无论小数点的哪一边,我总是具有固定的数字位数?
Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?
说我希望有6位数字,我想要这些结果:
Say I wish 6 digits, I want to have these results:
- 0.00123456789给出"0.00123"
- 1.23456789给出"1.23457"
- 123.456789给出"123.457"
- 0.0000000123456789给出"0.00000"
- 12345678.9给出"12345679"(发生溢出时,我想查看小数点后的所有数字)
- 4.2给出"4.20000"
我正在尝试使用double.ToString,但是找不到任何合适的格式字符串.
I'm experimenting with double.ToString, but cannot find any suitable format string.
已经尝试使用"G6"(有时会采用指数格式),"F6"(即将关闭,但0.123456789会给出7位数的"0.123457").
Already tried "G6" (gives sometimes exponential format), "F6" (comes close, but 0.123456789 gives "0.123457" which are 7 digits).
推荐答案
我认为您的某些示例是错误的. 但是我仍然认为我了解您想要实现的目标.
I think some of your examples are wrong. But I still think that I understand what you want to achieve.
我做了一个扩展方法.
I made an extension method.
public static class StringExtensionMethods
{
public static string ToString(this double d, int numberOfDigits)
{
var result = "";
// Split the number.
// Delimiter can vary depending on locale, should consider this and not use "."
string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
if(split[0].Count() >= numberOfDigits)
{
result = split[0].Substring(0, numberOfDigits);
}
else
{
result = split[0];
result += ".";
result += split[1];
// Add padding.
while(result.Count() < numberOfDigits +1)
result += "0";
result = result.Substring(0, numberOfDigits + 1);
}
return result;
}
}
我用您的示例来运行它:
I ran it with your examples:
double d0 = 0.00123456789;
double d1 = 1.23456789;
double d2 = 123.456789;
double d3 = 0.0000000123456789;
double d4 = 12345678.9;
double d5 = 4.2;
Console.WriteLine(d0.ToString(6));
Console.WriteLine(d1.ToString(6));
Console.WriteLine(d2.ToString(6));
Console.WriteLine(d3.ToString(6));
Console.WriteLine(d4.ToString(6));
Console.WriteLine(d5.ToString(6));
这是输出:
0.00123
1.23456
123.456
1.23456
123456
4.20000
0.00123
1.23456
123.456
1.23456
123456
4.20000
我认为这不是解决问题的最佳方法,但是我喜欢扩展方法.
I don't think this is the best way to solve it, but I like extension methods.
DoubleConverter类: http://1drv.ms/1yEbvL4
DoubleConverter class: http://1drv.ms/1yEbvL4
这篇关于如何用固定位数格式化浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!