2013-09-25 74 views
1

我有一個函數可以計算totalPrice並將其返回到totalPriceOutputLabel中。我的問題是,我需要將輸出格式化爲例如「1,222」。我知道如何將它轉換爲使用Visual Basic將字符串轉換爲貨幣格式

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

爲什麼* calculateButton_Click *和* totalPrice *做同樣的事情(格式除外)。編輯過程中出現錯誤? (* totalPrice *函數目前正在調用* totalPrice *) – Chris

+0

我做到了,那是我的錯誤。我更新了原始發佈。謝謝 – user1695704

+0

幹得好。謝謝。 – user1695704

回答

1

就像這樣:

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

它設totalPrice是支持.ToString()擴展與格式參數一個Double或其他數字類型。

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,因爲參數已經是數字類型。
+0

在實現您所寫的內容時,我收到一個關於指向(「C2」)的未處理異常的錯誤。這個錯誤並不能解釋如何處理這個問題。 – user1695704

+0

@ user1695704什麼類型返回函數* totalPrice *? Cab你用整個方法編輯問題? – Chris

+0

方法更新。謝謝。 – user1695704