If you want to take the integral and fractional parts of a
Decimal.Truncate(Decimal) instead of a cast to
Decimal can represent much much larger numbers than
int, and you code will presently fail for such large numbers.
decimal intergralPart = Decimal.Truncate(d);
decimal fractionalPart = d - integralPart;
Simply dividing by 10 won't work anymore, because of course
decimal will keep the fraction part; rather, you can subtract the last 'digit' before dividing (see code below).
Note that everyone has changed the name of
i from your code:
i screams 'counter';
integralPart and such are much better names.
d having a sensible name is even more important, because it is part of the API exposed by the method. Good naming is really important.
Your method will always leave a "." after the integral part, even if there is no fractional part, except for the special case of
0. This seems inconsistent, and may or may not be a concern. (it's not what
Decimal.ToString() does, for instance).
You've not asked about performance, but I'll just point out that inserting at the start of a string-builder is more expensive than adding to the end (linear vs. amortised constant). This means you code is actually quadratic in the string-length of the value. You could make it linear by writing the integral part backwards, and then reversing it, but who cares.
Code based on tinstaalf's code, but using
decimal integral and fractional parts (should hopefully work for any
static string DecToStr(decimal value)
StringBuilder sb = new StringBuilder();
bool negative = value < 0M;
value = -value; // decimals are symetrical, so this can't go wrong
SplitDecimal(value, out integral, out fractional);
if (integral > 0M)
while (integral > 0)
decimal digit = Decimal.Truncate(integral % 10);
integral = (integral - digit) / 10M;
sb.Append('0'); // explicitly add a "0" if the integral part is zero
sb.Insert(0, '-'); // add a - if we were negative
if (fractional != 0) // only add a fraction part if we have one to add
sb.Append('.'); // only add a . if we have a fraction part
while (fractional != 0)
decimal digit; // `digit` is perhaps more meaningful than `temp`
SplitDecimal(fractional * 10, out digit, out fractional);
static void SplitDecimal(decimal value, out decimal integral, out decimal fractional)
integral = Decimal.Truncate(value);
fractional = value - integral;