【问题标题】:String-from-decimal error十进制字符串错误
【发布时间】:2012-07-16 02:13:18
【问题描述】:

我有一个值为 0.00 的文本框,然后我得到一个错误转换...但我 已经做了一个 0.00 的例子,而不是来自文本框,它正在工作。我该如何解决这个问题?

    Dim _Total, _Deduct, _Charges As String
    Dim _sss, _tax, _pf, _ph, _loan, _others, _hdmf, _cola, _allowance As Decimal

如果文本框和注释此行有效,则此行.. 但我使用此行不工作..

    _sss = txtSSS.Text : _ph = txtPH.Text : _tax = txtInTax.Text : _pf = txtPF.Text
    _loan = txtLoan.Text : _hdmf = txtHDMF.Text : _others = txtOther.Text
    _cola = txtCola.ToString : _allowance = txtAllowance.ToString

这一行是我给定的示例值...相同的值但文本框不工作..这是工作

    'This code when I uncomment.. this work..
    '_sss = "0.00": _ph = "0.00" : _tax = "0.00" : _pf = "0.00"
    '_loan = "0.00" : _hdmf = "50.00" : _others = "0.00"
    '_cola = "0.00" : _allowance = "0.00"

    _Charges = CDec(_cola) + CDec(_allowance)
    _Deduct = CDec(_sss) + CDec(_tax) + CDec(_pf) + CDec(_ph) + CDec(_loan) + CDec(_hdmf) + CDec(_others)

    _Total = CDec(_Charges) - CDec(_Deduct)

    lblDeduct.Text = Format((_Deduct), "currency")
    lblTotal.Text = FormatCurrency((_Total), 2, TriState.True, TriState.False, TriState.True)

【问题讨论】:

    标签: vb.net visual-studio-2010 sql-server-2008 vb.net-2010


    【解决方案1】:

    使用Decimal.TryParse:

    <!-- language : lang-vb -->
    If Not Decimal.TryParse(txtSSS.Text, _sss) Then
        ' do something if the value doesn't convert
    End If
    

    根据您的评论并使用您的代码,看看这是否适合您(我使用 0 作为默认值)。如果您没有打开Option Strict,请帮自己一个忙。

    从上面Option Strict链接:

    将隐式数据类型转换限制为仅扩展转换,禁止后期绑定,并禁止导致 Object 类型的隐式类型。

    Private Sub CalculateCurrency()
        If Not Decimal.TryParse(txtSSS.Text, _sss) Then _sss = 0D
        If Not Decimal.TryParse(txtPH.Text, _ph) Then _ph = 0D
        If Not Decimal.TryParse(txtInTax.Text, _tax) Then _tax = 0D
        If Not Decimal.TryParse(txtPF.Text, _pf) Then _pf = 0D
        If Not Decimal.TryParse(txtLoan.Text, _loan) Then _loan = 0D
        If Not Decimal.TryParse(txtHDMF.Text, _hdmf) Then _hdmf = 0D
        If Not Decimal.TryParse(txtOther.Text, _others) Then _others = 0D
        If Not Decimal.TryParse(txtCola.Text, _cola) Then _cola = 0D
        If Not Decimal.TryParse(txtAllowance.Text, _allowance) Then _allowance = 0D
    
        _Charges = CStr(_cola + _allowance)
    
        _Deduct = CStr(_sss + _tax + _pf + _ph + _loan + _hdmf + _others)
    
        _Total = CStr(CDec(_Charges) - CDec(_Deduct))
    
        lblDeduct.Text = Format((_Deduct), "currency")
        lblTotal.Text = FormatCurrency((_Total), 2, TriState.True, TriState.False, TriState.True)
    End Sub
    

    【讨论】:

    • hmm.. 先生.. 如果文本框的值是动态的并且可以通过 textchange 更改.. 我真的不知道如何工作.. TY 的回复..
    • @DeorwinBensurto 把它放在 TextBox 的 TextChanged 事件中
    • 仍然不知道解决这个问题的好方法先生..我实际上使用货币价值的计算..但仍然没有解决..
    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2019-07-27
    • 2017-03-22
    相关资源
    最近更新 更多