c# - 将 double 格式化为字符串并在第一个数字出现后显示 2 个位置

标签 c#

我的结果应该是这样的:

double n1 = 0.024862;
double n2 = 1357512.15;
double n3 = 124.187;
Output:
N1: 0.0248
N2: 1,357,512.15
N3: 124.18

这是我目前拥有的:

n1.ToString("#,0.00", CultureInfo.InvariantCulture);

这适用于大数字,但如果我有像 0.0005524 这样的数字,我将得到 0.00,我想要 0.000552

第一次出现数字后的2位数字

最佳答案

不确定这是否是您想要的:

private static string NFiguresAfterFirstDecimal(double d, int figures)
{
    int c = 0;
    while (Math.Abs(d) < 1.0 && Math.Abs(d) > 1E-50){
        d *= 10.0;
        c++;
    }
    d = Math.Round(d, figures) / Math.Pow(10.0, c);
    if (Math.Abs(d) < 1.0 && c > 2)
        return ((decimal) d).ToString();
    else
        return d.ToString("#,0.00", CultureInfo.InvariantCulture);
}

测试运行:

double[] list = {0.00055243435, 0.00, 0.1, 1357512.157, 1.0001, 1.1, 123.445};

foreach(double d in list)
    Console.WriteLine(NFiguresAfterFirstDecimal(d,2));

输出:

0.000552
0.00
0.10
1,357,512.16
1.00
1.10
123.44

关于c# - 将 double 格式化为字符串并在第一个数字出现后显示 2 个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857358/

相关文章:

c# - WPF - 使用 pack URI 从转换器返回图像

javascript - 获取 div javascript 文件中的按钮

c# - (Char)174 返回 (Char)0174 的值,为什么?

c# - MongoDB - 在 C# 中映射 map-reduce 集合

c# - 将 Unityscript 转换为 C# : what does something like if(format & 2) mean?

C#-WPF 奇怪的异步行为

c# - 具有受限类型参数的通用类

c# - WCF 托管在 WPF 中,我如何从 wcf 更改 MainWindow UI 中的控件?

c# - DataGrid 行内容垂直对齐

c# - 如何将存储在 redis 中的数据与数据库中的数据同步?