string 在VB.NET中将字符串转换为十进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6055847/
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-09 01:06:48  来源:igfitidea点击:

Convert a string to decimal in VB.NET

vb.netstringformatdecimal

提问by user709787

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)

回答by Slappy

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

使用Decimal.Parse转换为十进制数,然后用.ToString("format here")转换回一个字符串。

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.

您将不得不转换为 Visual Basic。

回答by chrissie1

Use Decimal.TryParse

使用 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

回答by Rohit

For VB.NET:

对于 VB.NET:

CDec(Val(string_value))

For example,

例如,

CDec(Val(a))

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

结果将是40000D或者如果 a = "400.02" 的值,那么它将是400.02D

回答by devinbost

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

回答by Developer

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"));

回答by Paul A. Quiamco

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

回答by user709787

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