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;
}
这篇关于格式化带有公制前缀的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:格式化带有公制前缀的数字?
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01