在薪酬计算程序中,“从字符串转换为Double类型无效”

时间:2016-10-04 02:24:27

标签: vb.net

我正在尝试一个计算游乐园员工每周工资的项目。

当我运行它并在文本框中输入数字时,我收到错误消息“从字符串转换为Double类型无效”。

有人可以解释我哪里出错吗?

Dim ticketCollection As Double
Dim foodService As Double
Dim cleaningService As Double
Dim ridingAssistance As Double
Dim totalAmount As Double
Dim totalCollectionPay As Double
Dim totalFoodPay As Double
Dim totalCleaningPay As Double
Dim totalRidingPay As Double

ticketCollection = txtCollection.Text
foodService = txtFood.Text
cleaningService = txtCleaning.Text
ridingAssistance = txtRide.Text

totalCollectionPay = ticketCollection * 5
totalFoodPay = foodService * 10
totalCleaningPay = cleaningService * 6
totalRidingPay = ridingAssistance * 5

totalAmount = totalCollectionPay + totalFoodPay + totalCleaningPay + totalRidingPay

lblTotalDue.Text = totalAmount

3 个答案:

答案 0 :(得分:1)

我认为它会起作用......试试吧

Dim ticketCollection As Double
Dim foodService As Double
Dim cleaningService As Double
Dim ridingAssistance As Double
Dim totalAmount As Double
Dim totalCollectionPay As Double
Dim totalFoodPay As Double
Dim totalCleaningPay As Double
Dim totalRidingPay As Double

ticketCollection = val(txtCollection.Text)
foodService = val(txtFood.Text)
cleaningService = val(txtCleaning.Text)
ridingAssistance = val(txtRide.Text)

totalCollectionPay = ticketCollection * 5
totalFoodPay = foodService * 10
totalCleaningPay = cleaningService * 6
totalRidingPay = ridingAssistance * 5

totalAmount = totalCollectionPay + totalFoodPay + totalCleaningPay +      totalRidingPay

lblTotalDue.Text = totalAmount

如果您再次将错误的totalamount值分配给您的标签,

lblTotalDue.Text = val(totalAmount)

答案 1 :(得分:0)

你的声明都是双倍的。当它来自

{{1}}

它变成一个字符串,所以正确地将它转换为双倍 see msdn conversion guide here

答案 2 :(得分:0)

尝试将输入转换为Double。 CDbl将字符串类型的输入转换为double。同时将option strict on放在代码顶部以查看发生的任何隐式转换,这总是好的,我建议在编码任何项目时始终启用此功能。我在另一个答案中看到他们要求做同样的事情,但是val,这可能也有效,但val会有一些有趣的副作用,example。因此,最好不要使用valThis question也有一个很好的答案可以解释这一点以及如何尝试使用TryParse方法,它使用整数,但您只需要用double替换它。但我会首先尝试下面的内容。

ticketCollection = CDbl(txtCollection.Text)
foodService = CDbl(txtFood.Text)
cleaningService = CDbl(txtCleaning.Text)
ridingAssistance = CDbl(txtRide.Text)

并使用此行lblTotalDue.Text = totalAmount即可使用lblTotalDue.Text = CStr(totalAmount)CStr转换为字符串。