简体   繁体   English

C#中的千位分隔符可获取更多的小数点

[英]Thousand separator in C# for more number of decimal points

I need thousand separator in C# code or VB which I will be using in BluePrism code stage. 我需要在BluePrism代码阶段使用的C#代码或VB中使用千位分隔符。 One of the questions in stack overflow gave me the solution upto some extent but not complete. 堆栈溢出中的问题之一在某种程度上给了我解决方案,但并不完整。

I am having more than two digits after decimal point and I need the number to have thousand separator and retain all the decimal values. 我在小数点后有两位以上的数字,我需要该数字具有千位分隔符并保留所有十进制值。

Out = String.Format("{0:N}%", In);

If In is -137855027.5123456 Out value is -137,855,027.51%, but I need all the values after the decimal point. 如果In是-137855027.5123456 Out的值是-137,855,027.51%,但是我需要小数点后的所有值。

If you have a number like this: 如果您有这样的数字:

double number = -137855027.5123456;

You may use {0:NXX} where XX is the number of decimals you want after the decimal point. 您可以使用{0:NXX} ,其中XX是小数点后所需的小数位数。 For example: 例如:

var output = string.Format("{0:N6}%", number);    // -137,855,027.512346%

You should choose the maximum number of digits you want after the decimal point. 您应该选择小数点后所需的最大位数。 Note that if there aren't enough digits, the rest will be filled with zeros (eg, 123.1230000). 请注意,如果没有足够的数字,其余数字将填充零(例如123.1230000)。 If you want to avoid that, you may do something like this: 如果要避免这种情况,可以执行以下操作:

var output = string.Format("{0:N10}", number).TrimEnd('0') + "%";

Another solution inspired by this answer would be: 受此答案启发的另一个解决方案是:

var output = number.ToString("#,#.#############################") + "%";

Try them all online: 在线尝试所有功能:

You can build your own patterns according to your input-number: 您可以根据输入数字构建自己的模式:

decimal myNumber = -137855027.5123456m;

// two decimals..
string pattern = "#,##0." + "".PadLeft(2, '0');
Console.WriteLine("Pattern: " + pattern);
Console.WriteLine(myNumber.ToString(pattern));
Console.WriteLine();

// 20 decimals..
pattern = "#,##0." + "".PadLeft(20, '0');
Console.WriteLine("Pattern: " + pattern);
Console.WriteLine(myNumber.ToString(pattern));
Console.WriteLine();

// Calculate how much decimals are needed..
int decimals = BitConverter.GetBytes(decimal.GetBits(myNumber)[3])[2];
pattern = "#,##0." + "".PadLeft(decimals, '0');
Console.WriteLine("Pattern: " + pattern);
Console.WriteLine(myNumber.ToString(pattern));
Console.WriteLine();

// If you only want to set the decimals this version would be easier:
Console.WriteLine(myNumber.ToString("{0:N" + decimals + "}"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM