2011-02-23 78 views
1

在VBScript中我正在尋找將在1000的格式,或者1000,000或更大的數以百萬計回報的數字如下函數格式化數字:與單位符號「K」和「m」

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是整數。

+0

在僞代碼的線槽: 如果(X> 1000000) 返回X/1000000 + 「m」 個 否則如果(X> 1000 ) return x/1000 +「k」 ^寫這樣一個函數的任何問題,或者你只是尋找特定的VB語法你困惑...或尋找一種實用的方法,做一些更通用的格式? – shaunhusain 2011-02-23 01:47:29

+0

vb特定代碼... – van 2011-02-23 01:49:30

回答

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

侷限性:沒有舍入,只有結果