vb.net Visual Basic .NET 中的自定义数字格式字符串

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

Custom numeric format string in Visual Basic .NET

.netvb.netstring-formatting

提问by edkalel

I'm trying to learn Visual Basic .NET step by step, but now I have a problem with a custom numeric format string using the String.Format() method.

我正在尝试逐步学习 Visual Basic .NET,但现在我遇到了使用 String.Format() 方法的自定义数字格式字符串的问题。

I have an Integer variable like this

我有一个像这样的整数变量

Dim x As Integer = 123456

Dim x As Integer = 123456

and I want to format it to 1,234.56 with the String.Format() method. I believed that the following was the correct format but it doesn't work:

我想使用 String.Format() 方法将其格式化为 1,234.56。我认为以下是正确的格式,但它不起作用:

String.Format("#,###.##", x)

String.Format("#,###.##", x)

What is the correct format string to get the result that I need?.

获得我需要的结果的正确格式字符串是什么?

回答by kdnooij

As an alternative to what Plutonix is saying, you could do it using a simple function:

作为 Plutonix 所说的替代方案,您可以使用一个简单的函数来完成:

Public Function FormatInt(format As String, arg As Integer) As String
    Dim ArgString As String = arg.ToString
    Dim Result As String = ""

    Dim FormatIndex As Integer = 0
    For i As Integer = 0 To format.Length - 1
        If format.Substring(i, 1) = "#" Then
            Result = Result + ArgString.Substring(FormatIndex, 1)
            FormatIndex = FormatIndex + 1
        Else
            Result = Result + format.Substring(i, 1)
        End If
    Next

    Return Result
End Function

This might not be the best solution, but it is very simple to use:

这可能不是最好的解决方案,但使用起来非常简单:

Dim x As Integer = 123456    
FormatInt("#,##.##",x)

Too make it work the other way around (reverse it) you can just reverse the process. It doesn't work like the String.Format() method does, but I believe it suits your needs

太让它以相反的方式工作(逆转它),你可以逆转这个过程。它不像 String.Format() 方法那样工作,但我相信它适合您的需求

回答by Hamied

x.tostring("n2")

It will display your result as 123,456.00 in your example above.

在上面的示例中,它会将您的结果显示为 123,456.00。

Not you can use N or N0 up to any digit you want like N2 , N3 , ....

不是你可以使用 N 或 N0 到任何你想要的数字,比如 N2 , N3 ,....