[英]Convert a string to decimal in VB.NET
將字符串轉換為十進制的最簡單方法是什么?
輸入:
a = 40000.00-
輸出將是
40,000.00-
我試着使用這段代碼:
Dim a as string
a = "4000.00-"
a = Format$(a, "#,###.##")
console.writeline (a)
使用Decimal.Parse
轉換為十進制數,然后使用.ToString("format here")
轉換回字符串。
Dim aAsDecimal as Decimal = Decimal.Parse(a).ToString("format here")
最后的方法(不推薦):
string s = (aAsDecimal <0) ? Math.Abs(aAsDecimal).ToString("##,###0.00") + "-" : aAsDecimal .ToString("##,###0.00");
您將不得不翻譯為Visual Basic。
使用Decimal.TryParse
Dim a as string
Dim b as Decimal
If Decimal.TryParse(a, b) Then
a = b.ToString("##,###.00")
Else
a = "can not parse"
End If
對於VB.NET:
CDec(Val(string_value))
例如,
CDec(Val(a))
結果將是40000D
或如果a =“400.02”的值那么它將是400.02D
。
Sub Main()
Dim convert As Func(Of String, Decimal) = _
Function(x As String) Decimal.Parse(x) ' This is a lambda expression.
Dim a = convert("-16325.62")
Dim spec As String = "N"
Console.WriteLine("{1}", spec, a.ToString(spec))
'Console.ReadLine() ' Uncomment to see value in Console output.
End Sub
以下工作對我來說很好,但我不知道它是否正確。
double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));
Dim D@ = CDec(TextBox1.Text) '//convert string to decimal with short
這段代碼有效,但很長:
Dim a as string
Dim b as decimal
a = "4000.00-"
b = a
If b >= 0 then
console.writeline (b.ToString("##,###.00"))
Else
b = Math.Abs(b)
console.writeline (b.ToString("##,###.00") & "-")
End if
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.