VB.net:如何格式化金钱/数字?

时间:2015-07-05 13:55:19

标签: wpf vb.net formatting currency

我不知道如何提出格式化数字的代码。

Example:

Input into textbox : 1000
Result in textbox2: 1k

Example:

Input into textbox : 1000000
Result in textbox2: 1m

Example:

Input into textbox : 1000000000
Result in textbox2: 1b

Example:

Input into textbox : 2147483647
Result in textbox2: 2.147483647b
Example:

Input into textbox : 583967
Result in textbox2: 583.967k

我该怎么做?请帮忙!!

2 个答案:

答案 0 :(得分:2)

这可以通过条件算术分组来实现

Imports System

Public Module Module1
    Public Sub Main()
        Dim Input As ULong
        Console.Write("Enter a number: ")
        Input = Convert.ToUInt64(Console.ReadLine())
        Console.WriteLine(FormatNumber(Input))
    End Sub

    Public Function FormatNumber(ByVal Input As ULong) As String
        Dim Result As String = Input.ToString()

        If Input >= 1000000000
            Result = String.Format("{0}b", Input / 1000000000) 
        Else If Input >= 1000000
            Result = String.Format("{0}m", Input / 1000000)
        Else If Input > 1000
            Result = String.Format("{0}k", Input / 1000)
        End If

        Return Result
    End Function
End Module

结果:

Enter a number: 123000000000
123b

Demo

答案 1 :(得分:1)

.NET没有数字组的文字常量 但您可以使用Custom Numeric Format的数字缩放,并将您的角色添加到自定义格式

Private Function GetMyFormat(value As Int64) As String
    Select Case Math.Abs(value)
        Case Is < 1000000
            Return "0,.############'k'"
        Case Is < 1000000000
            Return "0,,.############'m'"
        Case Else
            Return "0,,,.############'b'"
    End Select
End Function

然后将其与.ToString方法

一起使用
Dim number As Int64 = 109106
Dim format As String = Me.GetMyFormat(number)
Me.TextBox2.Text = number.ToString(format)

或创建扩展方法

<Extension>
Public Function ToStringWithMyFormat(this As Int64)
    Dim format As String = "0,,,.############'b'"
    Select Case Math.Abs(this)
        Case Is < 1000000
            format = "0,.############'k'"
        Case Is < 1000000000
            format = "0,,.############'m'"
    End Select        
    return this.ToString(format)
End Function

并使用它:

Dim number As Int64 = 109106
Me.TextBox2.Text = number.ToStringWithMyFormat()