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)
Dim money = 1234.556789D
money.ToString("C") ' Yields $1,234.56 (notice the rounding & truncating)
money.ToString("C99") ' Yields $1,234.556789000000000000....0 -- close but not perfect, those trailing zeros are unwanted.
' I want something that would result in this...
money.ToString("??") ' Yields $1,234.56789
' likewise....
money = 0.1D
money.ToString("??") ' Yields $0.10 (notice that it at least matches the culture's currency format -- two decimal places)
Assuming all of the users of this application would be using en_US rules I could make that “??” be something hard-coded like “$#,##0.00################################################################” — but that makes my stomach churn. Is there a built-in way to accomplish what I’m after?
Seeing that there doesn’t seem to be a built-in way of doing this, I ended up rolling my own extension method that looks like…
I noted some negligible loss of precision. We (or anybody probably) wouldn’t be dealing with decimal values fractional enough enough to ever run into the limitations.