I have the need to format a decimal number as currency but I do not wish for any rounding to occur in the process.
For example (example culture is en-US)
<
You could do something like this...
var money = 1234.556789D;
Console.WriteLine(money.ToString(GetFormat(money)));
money = .1D;
Console.WriteLine(money.ToString(GetFormat(money)));
using the following method to get the format string...
static string GetFormat(double input)
{
// get the number of decimal places to show
int length = input.ToString().Length - input.ToString().IndexOf(".") - 1;
// return the currency format string to use with decimal.ToString()
return string.Format("C{0}", length < 2 ? 2 : length);
}
If you wanted to take it a step further, you could also wrap all of this into an extension method so that you didn't have to call the GetFormat() method from inside ToString() - that might make things look a bit cleaner.