开发者

Formatting numbers with unit symbols "k" and "m"

In VBScript I'm looking for开发者_开发问答 a function that will return the numbers in the format 1000s or if 1000,000 or greater in millions as follows:

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 

Where x, y, z, q are integers.


@van: Working example --

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


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

It could be it wouldn't work for integers, because I never have seen integers with thousand separator formatting. Just place a question mark in the regular expressions behind the comma, and it will also work for numbers without thousand separators. Like: "(,?\d{3}){2}$" and ",?\d{3}$"

Limitations: No rounding, only trunking of the results

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜