使用单位符号“k”和“m”格式化数字

时间:2011-02-23 01:43:28

标签: vbscript number-formatting

在VBScript中,我正在寻找一个函数,它将返回1000s格式的数字或1000,000或更高的数百万,如下所示:

x = 100,000 then return 100k
y = 500,000 then return 500k
z = 5,000,000 then return 5m
q = 25,000,000 then return 25m 

其中x,y,z,q是整数。

2 个答案:

答案 0 :(得分:1)

@van:工作示例 -

Option Explicit

Function NumFormat(ByRef iNumber, ByRef blnFixed)
    Dim sNumber

    If iNumber >= 1000000 Then
        If NOT blnFixed Then
            sNumber = (iNumber / 1000000) & "m"
        Else
            sNumber = Fix(iNumber / 1000000) & "m"
        End If
    ElseIf iNumber >= 100000 Then
        If NOT blnFixed Then
            sNumber = (iNumber / 1000) & "k"
        Else
            sNumber = Fix(iNumber / 1000) & "k"
        End If
    ElseIf iNumber >= 10000 Then
        If NOT blnFixed Then
            sNumber = (iNumber / 1000) & "k"
        Else
            sNumber = Fix(iNumber / 1000) & "k"
        End If
    ElseIf iNumber >= 1000 Then
        If NOT blnFixed Then
            sNumber = (iNumber / 1000) & "k"
        Else
            sNumber = Fix(iNumber / 1000) & "k"
        End If
    End If

    NumFormat = sNumber
End Function

Response.Write NumFormat(56120000, True) & "<br>"
Response.Write NumFormat(25050000, False) & "<br>"
Response.Write NumFormat(255000, False) & "<br>"
Response.Write NumFormat(9009, True) & "<br>"
Response.Write NumFormat(3000, False) & "<br>"

答案 1 :(得分:0)

Option Explicit

Public Function convertAmount(a)
    a = CStr(a)
    Dim re : Set re = new RegExp

    ' Replace millions
    re.Pattern ="(,\d{3}){2}$"
    a = re.replace(a, "m")
    ' Replace kilo's
    re.Pattern =",\d{3}$"
    a = re.replace(a, "k")

    convertAmount = a
End Function

' Testcode
MsgBox convertAmount("1,234,567")

它可能不适用于整数,因为我从未见过具有千位分隔符格式的整数。只需在逗号后面的正则表达式中放置一个问号,它也适用于没有千位分隔符的数字。喜欢: "(,?\d{3}){2}$"",?\d{3}$"

限制:没有舍入,只有结果的中继