用逗号格式化小数,保留尾随零 [英] Format decimal with commas, preserve trailing zeros

查看:41
本文介绍了用逗号格式化小数,保留尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将十进制转换为字符串,并以逗号作为成千上万的分隔符,并保持与十进制创建时相同的精度.(将有2-5个有效数字)

I'd like to convert a decimal to a string, with commas as thousands seperators, and preserve the same precision the decimal was created with. (Will have 2-5 significant digits)

        decimal d = 1234.4500M;

        //I'd like "1,234.4500"

        var notRight = d.ToString("###,###.#######");     //1,234.45
        var alsoNotRight = d.ToString("###,###.00000");;  //1,234.45000
        var notRightEither = d.ToString("N");    //1,234.45
        var notRightEither2 = d.ToString("G");   //1234.45000

是否存在没有手动解析字符串的内置方法?如果没有单一格式的字符串,最简单的方法是什么?

Is there no built in way to do this without parsing the string manually? If there is no single format string, what's the easiest way to do this?

推荐答案

根据

According to the documentation, a decimal number preserves the trailing zeros. You can display them if you use the "G" specifier or no specifier at all. They are lost when you use one of the specifiers that includes a thousand separator.

如果要在转换为字符串时指定尾随零的数目,可以通过添加精度说明符(0到99位数字),例如:

If you want to specify the number of trailing zeros when converting to string, you can do it by adding a precision specifier (0 to 99 digits) after the format character, like this:

decimal d=1234.45M;
var numberAsString=d.ToString("N4");

结果将是

 1,234.4500

更新:您可以使用 Decimal.GetBits 获取小数位数a>方法,该方法返回数字的二进制表示形式.小数位数存储在第四个元素的第16-23位(第三个字节)中.

UPDATE: You can get the number of decimal digits using the Decimal.GetBits method which returns the binary representation of the number. The number of decimals is stored in bits 16-23 (third byte) of the fourth element.

返回的数组的第四个元素包含比例因子和符号.它由以下部分组成:

...

第16到23位必须包含0到28之间的指数,这表示10的幂可以除以整数.

使用所有数字获取字符串表示形式可以像这样完成:

Getting a string representation using all digits can be done like this:

decimal d=1234.45000M;
var nums=Decimal.GetBits(d);
var decimals=BitConverter.GetBytes(nums[3])[2];
var formatStr="N"+decimals;
d.ToString(formatStr);

会产生

1,234.45000

这篇关于用逗号格式化小数,保留尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆