將字符串轉換爲十進制的最簡單方法是什麼?在VB.NET中將字符串轉換爲十進制
輸入:
a = 40000.00-
輸出將被
40,000.00-
我試圖用這個代碼:
Dim a as string
a = "4000.00-"
a = Format$(a, "#,###.##")
console.writeline (a)
將字符串轉換爲十進制的最簡單方法是什麼?在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。
我嘗試這個,但我想要的結果是否定的應該在最後。 昏暗一個作爲字符串 一個= 「4000.00-」 一個= Decimal.Parse的(a)的ToString( 「##,###。00」) console.writeline的(a) '導致4,000.00 – user709787 2011-05-19 15:03:25
只是一個猜測,但你有沒有嘗試「##,### 0.00-」 – Slappy 2011-05-20 01:09:38
否則有未經推薦的方法:(a <0)? Math.Abs(a).ToString(「##,### 0.00」)+「 - 」:a.ToString(「##,### 0.00」); – Slappy 2011-05-20 01:14:11
以下工作適合我,但我不知道它是否正確。
double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));
中間線是不必要的。你將一個double轉換爲一個字符串,然後再將它解析爲double。現在,如果你試圖截斷額外的小數位(即:40000.0001到40000.00),這將起作用,但是Math.Round(a,2)會更有效率。 – dwilliss 2015-01-08 19:40:48
使用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
此代碼的工作,但它是相當長的:
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
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
對於VB.NET:
CDec(Val(string_value))
例如,
CDec(Val(a))
其結果將是40000D
,或者如果要=「400.02」,那麼這將是400.02D
的值。
http://blog.stevex.net/string-formatting-in-csharp/ – 2011-05-19 08:33:27