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

Viewed 541

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

2 Answers

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})"
regex2.Pattern = ",$"
output = regex1.Replace(input, "$1,")
output = 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.

Or without regex:

Mid(CStr(w_orimpo), 1, 3) & "," & Mid(CStr(w_orimpo), 4)

Or

Dim divider
divider = 10 ^ (Len(CStr(w_orimpo)) - 3)
w_orimpo = FormatNumber(w_orimpo / divider, 2)
Related