文本框计算不正确 [英] Textbox not calculating correctly

查看:97
本文介绍了文本框计算不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎以某种方式存在一个小错误,但对于我自己的一生,我无法修复它,我有一个小例程,该例程从Textbox输入中添加了一些数字,该函数在数学达到999.99之前一直可以正常工作,然后又回到1.00,我尝试了不同的格式,但无济于事,我的代码是.

I seem to have a small bug somehow but for the life of me I cannot fix it, I have a small routine that adds some numbers from Textbox inputs, this works fine until the maths reaches 999.99 then it goes back to 1.00, I have tried different formats but to no avail, my code is.

Public Sub DisplayTotalBalance()
       Dim AddTotalReceipts As Double = 123456.123
       Dim MinusTotalPayments As Double = 123456.123
       Dim GetTotalBalance As Double = 123456.123

       AddTotalReceipts = CDbl(Val(txtTotalReceipts.Text)).ToString("###,###.00")
       MinusTotalPayments = CDbl(Val(txtTotalPayments.Text)).ToString("###,###.00")

  GetTotalBalance = AddTotalReceipts.ToString("###,###.00") - MinusTotalPayments.ToString("###,###.00")
       txtBalance.Text = GetTotalBalance.ToString("###,###.00")

          End Sub


任何想法,我做错了什么或为什么它不会添加超过999.99.将非常感谢.


Any idea what i am doing wrong or why it will not add more than 999.99 would be greatly appreciated.

推荐答案

永远不要尝试使用字符串进行数学运算. br/> 您拥有双打数字-使用这些数字:

Never, ever, try to do maths with strings.
You have the numbers as Doubles - use those:

GetTotalBalance = AddTotalReceipts - MinusTotalPayments
txtBalance.Text = GetTotalBalance.ToString("###,###.00")


所有这些ToString确实不是必需的.
您有三个已经是数字的双精度数,不需要任何格式.
您可以使用这些数字类型进行计算,只有最后才需要对其进行格式化以进行输出.
据我所知,如果txtTotalReceipts.Text或txtTotalPayments无法转换为数字类型,那么您的代码还会引发异常.
您应该检查 TryParse方法 [
All those ToStrings are really not necessary.
You have three doubles which are already numeric and do not need any format.
You can calculate with these numeric types and only in the end do you need to format it for output.
What''s also wrong, as far as I can see, if txtTotalReceipts.Text or txtTotalPayments is not convertible to a numeric type your code is going to throw an exception.
You should check the TryParse Method[^].
Public Sub DisplayTotalBalance()
    Dim addTotalReceipts As Double
    Dim minusTotalPayments As Double
    Dim getTotalBalance As Double
    
    If Double.TryParse(txtTotalReceipts.Text, addTotalReceipts) AndAlso Double.TryParse(txtTotalPayments.Text, minusTotalPayments) Then
        getTotalBalance = addTotalReceipts - minusTotalPayments
        txtBalance.Text = getTotalBalance.ToString("###,###.00")
    Else
        ' One of the two textboxes text could not be converted to double.
        txtBalance.Text = String.Empty
    End If
End Sub


希望对您有所帮助:)


Hope it helps :)


这篇关于文本框计算不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆