如何在 vb.net 中正确进行简单的数学百分比计算?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16143839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a simple maths percetange calculation correctly in vb.net?
提问by DreamTeK
Can this equation be reworked to a correctly formatted string?
这个方程可以改写为正确格式的字符串吗?
Dim Total = MyNumber / 100 * MyVAT
Produces error:
产生错误:
"Input string was not in a correct format"
回答by Tim Schmelter
You should really set Option Strictto on. Then this would never compile since MyNumberis a string(as you've commented).
你真的应该设置Option Strict为on. 然后这将永远不会编译,因为它MyNumber是一个字符串(正如您所评论的)。
You should first ensure that the input is numeric, for example with Decimal.TryParse:
您应该首先确保输入是数字,例如Decimal.TryParse:
Dim Total As Decimal
Dim num As Decimal
If Decimal.TryParse(MyNumber, num) Then
Total = num / 100 * MyVAT
End If
Now you can use Decimal.ToString(format)to convert it to a string with the desired format. For example(assuming you want two decimal places):
现在您可以使用Decimal.ToString(format)将其转换为具有所需格式的字符串。例如(假设您想要两位小数):
Dim output As String = Total.ToString("N2")
回答by Mandeep Singh
try with this statement
试试这个说法
Dim Total = Val(MyNumber) / 100 * Val(MyVAT)
回答by ????
use like below
使用如下
Total.ToString("#")
More Detail:- http://msdn.microsoft.com/en-in/library/0c899ak8.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
更多细节:- http://msdn.microsoft.com/en-in/library/0c899ak8.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

