Convert a string to decimal in VB.NET

好久不见. 提交于 2021-02-04 17:16:40

问题


What will be the easiest way to convert a string to decimal?

Input:

a = 40000.00-

Output will be

40,000.00-

I tried to use this code:

Dim a as string

a = "4000.00-"

a = Format$(a, "#,###.##")
console.writeline (a)

回答1:


Use Decimal.Parse to convert to decimal number, and then use .ToString("format here") to convert back to a string.

Dim aAsDecimal as Decimal = Decimal.Parse(a).ToString("format here")

Last resort approach (not recommended):

string s = (aAsDecimal <0) ? Math.Abs(aAsDecimal).ToString("##,###0.00") + "-" : aAsDecimal .ToString("##,###0.00");

You will have to translate to Visual Basic.




回答2:


Use 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



回答3:


For VB.NET:

CDec(Val(string_value))

For example,

CDec(Val(a))

The result will be 40000D or if the value for a = "400.02" then it will be 400.02D.




回答4:


The following works fine for me, but I don't know whether it is correct or not.

double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));



回答5:


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



回答6:


Dim D@ = CDec(TextBox1.Text) '//convert string to decimal with short



回答7:


This code works, but it is quite long:

 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


来源:https://stackoverflow.com/questions/6055847/convert-a-string-to-decimal-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!