Search code examples
vbscriptnumbersformat

How to put comma after 3 digits in numeric variable in vbscript?


i want to put a comma after 3 digits in a numeric variable in vbscript

w_orimpo = getvalue(rsmodifica , "w_orimpo")
w_orimpo = FormatNumber(w_orimpo,2)

The initial value of w_orimpo is 21960.

If I use FormatNumber I get the value 21,960.

But I would like to get the following one -> 219,60


Solution

  • We can handle this via a regex replacement:

    Dim input, output, regex1, regex2
    Set input = "21960"
    Set regex1 = New RegExp
    Set regex2 = New RegExp
    regex1.Pattern = "(\d{3})"
    regex1.Global = True
    regex2.Pattern = ",$"
    output = regex1.Replace(StrReverse(input), "$1,")
    output = StrReverse(regex2.Replace(output, ""))
    Rhino.Print output
    

    Note that two regex replacements are needed here because VBScript's regex engine does not support lookarounds. There is a single regex pattern which would have gotten the job done here:

    (\d{3})(?!$)
    

    This would match (and capture) only groups of three digits at a time, and only if those three digits are not followed by the end of the input. This is needed to cover the following edge case:

    123456 -> 123,456
    

    We don't want a comma after the final group of three digits. My answer gets around this problem by doing another regex replacement to trim off any trailing comma.