C# Convert decimal to string with specify format
decimal a = 12;
var b = a.ToString("N1"); // 12.0
a = 1.2m;
b = a.ToString(); // 1.2
a = 101m;
b = a.ToString("N10"); // 101.0000000000
a = 1.234m;
b = a.ToString("N10"); // 1.2340000000
For the second part of your question - where you want a total length of 10 then:
decimal a = 1.234567891m;
int numberOfDigits = ((int)a).ToString().Length;
var b = a.ToString($"N{9 - numberOfDigits}"); //1.23456789
//Or before C# 6.0
var b = a.ToString("N" + (9 - numberOfDigits)); //1.23456789
Basically ((int)number).ToString().Length
gives you the amount of digits before the .
(converting to int will remove the fractions) and then reducing that from the number of digits after the .
(and also -1 for the decimal point itself)
You can use .ToString()
to do this task:
decimal aDecimalVal = 10.234m;
string decimalString = aDecimalVal.ToString("#.000"); // "10.234"
aDecimalVal.ToString("#.00"); // "10.23"
aDecimalVal.ToString("#.0000"); // "10.2340"
The number of 0
after the .
in the format string will decide the number of places in the decimal string.
Updates: So you want to find the number of digits after the decimal points, So the changes in the code will be like the following:
decimal aDecimalVal = 10.2343455m;
int count = BitConverter.GetBytes(decimal.GetBits(aDecimalVal)[3])[2];
string formatString = String.Format("N{0}",count.ToString());
string decimalString = aDecimalVal.ToString(formatString); // "10.2343455"