C# Double 按有效数字 ToString

36 篇文章 0 订阅
32 篇文章 0 订阅

将double转换为n有效数字的字符

我找了各种帖子包括在微软文档搜索 ‘significant digits’;最接近的是ToString(“Gx”)
但是返回是不大于这个x有效位的字符串, 举例

double a=1.2;
string s=a.ToString("G3");

得到1.2而不是1.20

所以就写了一个函数

        string DoubleToStringSignificantDigits(double a, int SignificantDigits)
        {
            string formaterG = 'G' + SignificantDigits.ToString("N0");
            string strResult = a.ToString(formaterG);
            int resultLength = SignificantDigits;
            if (strResult.IndexOf('-') >= 0) resultLength++;
            if (strResult.IndexOf('.') >= 0) resultLength++;
            if (Math.Abs(a) < 1) resultLength++; //绝对值小于1,有一个整数0不算有效位
            if (strResult.Length < resultLength)
            {
                if (strResult.IndexOf('.') < 0)
                {
                    strResult += '.';
                    resultLength++;
		}
                strResult = strResult.PadRight(resultLength, '0');
            }
            return (strResult);
         }

结果

double[] x = new double[] { 100, 99, 12.12, 1.1234, 1.2, 0.2, 0.12345 , -0.2, -1.2, -123};
转换
DoubleToStringSignificantDigits(x[i], 3)
得到
100
99.0
12.1
1.12
0.200
0.123
-0.200
-1.20
-123

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值