我想在最后获得2位小数。 我在互联网上看到很多例子,但所有这些都可能是从变量格式化而不是直接从文本框格式化。 我也对一件事感到困惑。 这工作正常:
Dim d1 As Double
txtGAmt.Text = 1500
d1 = txtGAmt.Text
txtGAmt.Text = Format(d1, "0.00")
这里txt Gmat.Test将是1500.00
为什么以下代码不能按需运行?
txtGAmt.Text = 1500
txtGAmt.Text = Format(txtGAmt.Text, "0.00")
这给了我 txtGAmt.Text = 0.00
以下是我试过的东西,
txtGAmt.Text = Format("{0:n2}", txtGAmt.Text)
这给了我txtGAmt.Text = 1500(没有变化)
还试过formatcurrency
。
它运作良好,但我不希望数字之间的货币符号和逗号。
现在我的实际问题是我是否必须声明变量以在每个文本框中每次添加两个小数点?
函数Format使用数值而不是字符串。尝试使用Val函数或CDec将文本转换为数值。
txtGAmt.Text = 1500
txtGAmt.Text = Format(Val(txtGAmt.Text), "0.00")
在发布此答案并检查@David Wilson的回复后,我意识到如果您选择使用CDec而不是Val,如果文本框的内容是超出范围的数值,则可能会导致异常。那么,这是另一个解决方案:
txtGAmt.Text = 1500
Dim number As Decimal
If Decimal.TryParse(txtGAmt.Text, number) Then
txtGAmt.Text = Format(number, "0.00")
Else
'You can put your own logic here
txtGAmt.Text = 0
End If