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)
<
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...
Public Function ToUnroundedCurrency(ByVal value As Decimal) As String
Dim valueAsString As String = value.ToString() ' Some loss of precision happens here, but it is not a concern.
Dim decimalLocation As Integer = valueAsString.IndexOf(".")
' Get number of digits after the decimal place in the number
Dim numberOfDecimalPlaces As Integer = 0
If (decimalLocation > 0) Then numberOfDecimalPlaces = valueAsString.Length - decimalLocation - 1
' The currency formatter has a limit of 99 decimal places -- due to the decimal -> ToString() conversion above, this will never happen, but being defensive anyway.
If (numberOfDecimalPlaces > 99) Then
numberOfDecimalPlaces = 99
ElseIf (numberOfDecimalPlaces < CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits) Then
' also make sure we at least have the minimum required decimal places
numberOfDecimalPlaces = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits
End If
Return value.ToString("C" & numberOfDecimalPlaces)
End Function
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.