Formatting a number with a metric prefix?(格式化带有公制前缀的数字?)
问题描述
可能重复:
C#中的工程符号?
公制前缀是否优于科学记数法可能有争议,但我认为它有物理单位的用例.
Whether a metric prefix is preferable to the scientific notation may be up for debate but i think it has its use-cases for physical units.
我环顾四周,但似乎 .NET 没有内置类似的东西,还是我弄错了?任何实现这一点的方法都可以.
I had a look around but it seems .NET does not have anything like that built in, or am i mistaken about that? Any method of achieving that would be fine.
澄清一下:目标是将任何给定数字显示为浮点数或整数字符串,其值介于 1 和 999 之间,并带有相应的度量前缀.
As a clarification: The goal is to display any given number as a floating point or integer string with a value between 1 and 999 and the respective metric prefix.
例如
1000 -> 1k
0.05 -> 50m
1000 -> 1k
0.05 -> 50m
四舍五入:
1,436,963 -> 144 万
1,436,963 -> 1.44M
推荐答案
试试这个.我没有测试过,但它应该或多或少是正确的.
Try this out. I haven't tested it, but it should be more or less correct.
public string ToSI(double d, string format = null)
{
char[] incPrefixes = new[] { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };
char[] decPrefixes = new[] { 'm', 'u03bc', 'n', 'p', 'f', 'a', 'z', 'y' };
int degree = (int)Math.Floor(Math.Log10(Math.Abs(d)) / 3);
double scaled = d * Math.Pow(1000, -degree);
char? prefix = null;
switch (Math.Sign(degree))
{
case 1: prefix = incPrefixes[degree - 1]; break;
case -1: prefix = decPrefixes[-degree - 1]; break;
}
return scaled.ToString(format) + prefix;
}
这篇关于格式化带有公制前缀的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:格式化带有公制前缀的数字?


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01