简体   繁体   English

c#如何String.Format十进制无限小数位?

[英]c# how to String.Format decimal with unlimited decimal places?

I need to convert a decimal number to formatted string with thousand groups and unlimited (variable) decimal numbers: 我需要将十进制数转换为带有千组和无限(可变)十进制数的格式化字符串:

1234 -> "1,234"
    1234.567 -> "1,234.567"
    1234.1234567890123456789 -> "1,234.1234567890123456789"

I tried String.Format("{0:#,#.#}", decimal) , but it trims any number to max 1 decimal place. 我尝试了String.Format(“{0:#,#。#}”,十进制) ,但它将任意数字修剪为最多1位小数。

You can use # multiple times (see Custom Numeric Format Strings ): 您可以多次使用#(请参阅自定义数字格式字符串 ):

string.Format("{0:#,#.#############################}", decimalValue)

Or, if you're just formatting a number directly, you can also just use decimal.ToString with the format string. 或者,如果您只是直接格式化数字,也可以使用带有格式字符串的decimal.ToString

However, there is no way to include " unlimited decimal numbers". 但是,没有办法包含“ 无限小数”。 Without a library supporting arbitrary precision floating point numbers (for example, using something like BigFloat from Extreme Numerics ), you'll run into precision issues eventually. 如果没有支持任意精度浮点数的库(例如,使用来自Extreme Numerics的 BigFloat之类的东西),最终会遇到精度问题。 Even the decimal type has a limit to its precision (28-29 significant digits). 即使十进制类型也有其精度限制(28-29位有效数字)。 Beyond that, you'll run into other issues. 除此之外,你还会遇到其他问题。

As I've said, the decimal type has a precision of 28-29 digits. 正如我所说,十进制类型的精度为28-29位。

decimal mon = 1234.12345678901234567890123M;
var monStr = mon.ToString("#,0.##############################");
var monStr2 = String.Format("{0:#,0.##############################}", mon);

Here there are 30x # after the decimal separator :-) 这里有小数分隔符后的30x # :-)

I've changed one # with 0 so that 0.15 isn't written as .15 . 我用0更改了一个# ,因此0.15不会写为.15

this should do the trick 这应该可以解决问题

string DecimalToDecimalsString(decimal input_num)
        {            
            decimal d_integer = Math.Truncate(input_num); // = 1234,0000...
            decimal d_decimals = input_num-d_integer; // = 0,5678...

            while (Math.Truncate(d_decimals) != d_decimals)
                d_decimals *= 10; //remove decimals

            string s_integer = String.Format("{0:#,#}", d_integer);
            string s_decimals = String.Format("{0:#}", d_decimals);

            return s_integer + "." + s_decimals;
        }

replacing decimal with other types should work too. 用其他类型替换十进制也应该有效。

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

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