货币的格式不四舍五入 [英] Format currency without rounding

查看:268
本文介绍了货币的格式不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要格式化的十进制数为货币,但我不希望任何四舍五入发生的过程中。

I have the need to format a decimal number as currency but I do not wish for any rounding to occur in the process.

例如(例如文化是EN-US)

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)

假设所有这个应用程序的用户将使用EN_US规则,我能有这样的?是一些硬codeD,如$#,## 0.00 ################################## ############################## - 但是,让我的胃翻腾。是否有一个的内置的方式来完成我后?

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...

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

我注意到precision一些微不足道的损失。我们(或其他人可能)不会被处理十进制值分数够不够曾经遇到的限制。

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.

这篇关于货币的格式不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆