如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:21:22  来源:igfitidea点击:

How to do a simple maths percetange calculation correctly in vb.net?

asp.netvb.netstringmathpercentage

提问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 Stricton. 然后这将永远不会编译,因为它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")

Standard Numeric Format Strings

标准数字格式字符串

回答by Mandeep Singh

try with this statement

试试这个说法

 Dim Total = Val(MyNumber) / 100 * Val(MyVAT)