'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.
Solution 1:[1]
As I've said, the decimal type has a precision of 28-29 digits.
decimal mon = 1234.12345678901234567890123M;
var monStr = mon.ToString("#,0.##############################");
var monStr2 = String.Format("{0:#,0.##############################}", mon);
Here there are 30x# after the decimal separator :-)
I've changed one # with 0 so that 0.15 isn't written as .15 .
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xanatos |
| Solution 2 | Alex |
