C # like String.Format decimal with unlimited decimal places?

I need to convert a decimal number to a formatted string with thousands of 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 a maximum of 1 decimal place.

+7
source share
3 answers

You can use # several times (see Custom Number Format Strings ):

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

Or, if you just format the number directly, you can also just use decimal.ToString with the format string.

However, it is not possible to include "unlimited decimal numbers." Without a library that supports a number of arbitrary precision floating-point numbers (for example, using BigFloat from Extreme Numerics ), you will end up with accuracy problems. Even the decimal type has a precision limit (28-29 significant digits). In addition, you will encounter other problems.

+16
source

As I said, the decimal type has an accuracy of 28-29 digits.

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

Here, after the decimal separator, there is 30x # :-)

I changed one # to 0 so that 0.15 not written as .15 .

+5
source

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 the decimal with other types should work too.

+1
source

All Articles