我有一系列数字,可以是大整数,也可以是非常小的小数。我希望四位数以上的数字以科学计数法显示。
起初,我考虑了自定义数字格式
0.000E+0
,但这会将 E+0
放在任何少于四位数字的末尾。
在搜索时,建议我使用通用格式化程序
G4
,但这不会将小十进制数转换为科学记数法,例如,0.001234
仍然是0.001234
,而不是像我期望的那样变成1.234E-3
。
我需要一个满足以下条件的数字格式字符串:
0 -> 0
1234 -> 1234
12348 -> 1.235E3
0.123 -> 0.123
0.1234 -> 1.234E-1
0.001234 -> 1.234E-3
产生这种主动解析的被动数字格式字符串可能是一个艰巨的任务。但是,如果有任何方法可以使用扩展来满足您的用例,那么它会相当简单。这是在您的帖子中生成格式的第一遍:
public static class Extensions
{
public static string ToStringAuto<T>(this T o, int maxDigits = 4) where T : IConvertible
{
try
{
if (Convert.ChangeType(o, typeof(double)) is double @double)
{
string general = @double.ToString("G"); // Most compact
int digitsWithoutDecimal = general.Count(_ => _ != '.');
if (digitsWithoutDecimal > maxDigits)
{
var custom = @double.ToString("E3").Replace("E+", "E");
while (custom.Contains("E0")) custom = custom.Replace("E0", "E");
while (custom.Contains("-0")) custom = custom.Replace("-0", "-");
if((@double < 0) && custom[0] != '-')
{
custom.Insert(0, "-");
}
return custom;
}
else
{
return general;
}
}
}
catch { }
return o.ToString();
}
}
Console.WriteLine($"0 -> {0.ToStringAuto()}");
Console.WriteLine($"1234 -> {1234.ToStringAuto()}");
Console.WriteLine($"12348 -> {12348.ToStringAuto()}");
Console.WriteLine($"0.123 -> {0.123.ToStringAuto()}");
Console.WriteLine($"0.1234 -> {0.1234.ToStringAuto()}");
Console.WriteLine($"0.001234 -> {0.001234.ToStringAuto()}");
Console.WriteLine("\nCase of leading '-' where number should remain negative");
Console.WriteLine($"-0.001234 -> {(-0.001234).ToStringAuto()}");
Console.WriteLine("\nError tolerance for non-convertible input");
Console.WriteLine($"Azgard -> {"Azgard".ToStringAuto()}");
Console.ReadLine();