Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic number format in .NET?

I have a problem and cant find a solution. I have numbers (decimal) like 85.12343 or 100 or 1.123324. I want to format this in a way that the result is always 13 chars long including the separator.

100          --> 100.000000000
1.123324 --> 1.12332400000

I tried with toString, but failed. How could I do this?

Thanks :)

like image 982
grady Avatar asked Dec 08 '22 01:12

grady


1 Answers

int digits = 13;
decimal d = 100433.2414242241214M;
int positive = Decimal.Truncate(d).ToString().Length;
int decimals = digits - positive - 1; //-1 for the dot
if (decimals < 0)
    decimals = 0;
string dec = d.ToString("f" + decimals);

It will not remove digits from the whole part, only the fraction, when needed.

like image 153
Kobi Avatar answered Dec 09 '22 14:12

Kobi