vb.net 将字符串转换为十进制到字符串并返回到十进制

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

Convert string to decimal to string and back to decimal

vb.netstringtype-conversiondecimal

提问by Flo

I want to convert a string to a decimal then to a string and then to a decimal again.

我想将字符串转换为小数,然后再转换为字符串,然后再转换为小数。

I tried:

我试过:

Dim s As String = "0.7655"

CDec(sDec).ToString("0.00")  'results in: 7653,00
CDec(sDec).ToString 'results in: 7648
CDec(sDec).ToString("N") 'results in: 7.653,00

So none of these work!

所以这些都不起作用!

Is there no easy function to just convert the exact decimal to its string representation again? Seems like too much work for such a simple task!

有没有简单的函数可以再次将精确的十进制转换为其字符串表示?对于这样一个简单的任务来说,似乎工作太多了!

Preferably without formatting the string, because in that case I seem to know beforehand how many characters the resulting string should have. After converting it to string, I also want to convert it back to a decimal again.

最好不要格式化字符串,因为在这种情况下,我似乎事先知道结果字符串应该有多少个字符。将其转换为字符串后,我还想再次将其转换回十进制。

回答by Meta-Knight

In your current culture the decimal separator might be a comma instead of a dot. Using the invariant culture will always use the dot:

在您当前的文化中,小数点分隔符可能是逗号而不是点。使用不变文化将始终使用点:

Dim s As String = "0.7655"

Dim decValue As Decimal = Decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture)
Console.WriteLine(decValue.ToString())

回答by Jonathan

You should be able to acheive your answer by using the Parse method.

您应该能够使用 Parse 方法获得答案。

    Dim s As String = "0.7655"
    Dim c As Decimal = Nothing

    c = Decimal.Parse(s)

    Console.WriteLine(c)

You can then use the ToStringmethod to convert back to a string.

然后,您可以使用该ToString方法将其转换回字符串。