Visual Basic将字符串转换为货币格式

时间:2013-09-25 04:00:44

标签: vb.net function

我有一个计算totalPrice的函数,并在totalPriceOutputLabel中返回它。我的问题是,我需要将输出格式化为例如“1,222”。我知道如何使用

转换它
ToString("C2")

但我不确定如何在我的函数调用中附加它。有什么想法吗?

Public Class tileLimitedForm

Private enteredLength, enteredWidth As Double
Private enteredPrice As Decimal

Public Function area(ByRef enteredLength As Double, ByRef enteredWidth As Double)
    area = Val(enteredLength) * Val(enteredWidth)
End Function

Public Function totalPrice(ByRef enteredLength As Double, ByRef enteredWidth As Double)
    totalPrice = Val(area(enteredLength, enteredWidth)) * Val(enteredPrice)
End Function

Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click

totalPriceOutputLabel.Text = totalPrice(area(enteredLength, enteredWidth),enteredPrice).ToString("C2")

End Sub

1 个答案:

答案 0 :(得分:1)

就像这样:

totalPriceOutputLabel.Text = _
    totalPrice(area(enteredLength, enteredWidth), enteredPrice).ToString("C2")

假设 totalPrice Double或其他数字类型,支持带有格式参数的.ToString()扩展名。

修改

看到编辑后的问题:

 Public Class tileLimitedForm

        Private enteredLength, enteredWidth As Double
        Private enteredPrice As Decimal

        Public Function area(ByVal enteredLength As Double, ByVal enteredWidth As Double) As Double
            area = enteredLength * enteredWidth
        End Function

        Public Function totalPrice(ByVal enteredLength As Double, ByvalenteredWidth As Double) As Double
            totalPrice = area(enteredLength, enteredWidth) * enteredPrice
        End Function

        Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click
            totalPriceOutputLabel.Text = totalPrice(area(enteredLength, enteredWidth), enteredPrice).ToString("C2")
        End Sub
    End Class

注意:

  • 在这种情况下,您应该在函数中使用ByVal代替ByRef
  • 您的函数当前返回Object,因为您没有设置返回该函数的类型(您有Option Strict off)=>我添加了As Double
  • 无需使用Val,因为参数已经是数字类型。