0

我应该制作一个银行软件表单,允许用户创建账户并为任何账户进行存款和取款。但我不知道如何让它接受一个整数,一个小数点后面只有一个数字,或者一个小数点后面的第一个数字是 0。

Dim x As Decimal = Decimal.Parse(txtAmount.Text)
If (txtAmount.Text.IndexOf(".") <> -1 And txtAmount.Text.Substring(txtAmount.Text.IndexOf("." + 1)).Length > 2) Then
    MessageBox.Show("No fractions of a penny") 
    Exit Sub                            
End If

Dim a As CAccount = lbxCustomers.SelectedItem
a.deposit(x)

有人知道我在做什么错吗?

4

2 回答 2

0

Using the tryparse as suggested is most definitely a good starting point. One simple way to disregard extra digits is with the Truncate method:

    Dim x As Decimal
    If Decimal.TryParse(txtAmount.Text, x) Then
        x = Decimal.Round(x * 100) / 100
    Else
        MessageBox.Show("Only valid numbers please")
    End If

This will leave x with only a maximum of 2 decimal places. This also rounds the resulting value according to the value in the extra digits. This is useful for the Decimal type since it is prone to rounding errors and this will even them out.

于 2013-10-16T14:53:00.353 回答
0

您可以将当前值与舍入值进行比较。如果两者相等,你就知道没有更多的数字了。如果您还想限制零(2.0000 将通过),这将不起作用。

    Dim val As Decimal

    val = 2.2345

    If val * 100 = Math.Floor(val * 100) Then
        ' Has 2 or less digit
    Else
        ' Has more than 2 digit
    End If
于 2013-10-16T15:14:55.047 回答