Since
Format() apparently doesn't have an option to add thousands separators (commas in my case) to its results, I use the function below to get the job done (after using Format() if necessary). It takes a single argument with optional negative sign and fractional part, calculates the number N of separators that will be required, generates appropriate RegEx and replacement patterns based on N (assumes numbers from -2^63 to (2^63-1), the 64-bit extremes), and applies them to the input. Is there a better way? (I chose a RegEx approach to avoid looping).
Code: Select all
ThouSep(X)
{
N := (StrLen(Floor(Abs(X))) - 1) // 3
Pat := "^(-?\d{1,3})" . SubStr("(\d{3})(\d{3})(\d{3})(\d{3})(\d{3})(\d{3})", 1, 7*N) . "(\.\d*)?$"
Rep := "$1" . SubStr(",$2,$3,$4,$5,$6,$7", 1, 3*N) . "$" . N+2
Return, RegExReplace(X, Pat, Rep)
}
Modify as needed for different thousands and decimal separators (or be ambitious and read them from the Registry
).
Update: See the first reply for a superior RegEx solution that uses a single generic pattern. Needs modification to handle negative numbers, but impressive nonetheless.
Update 2: I'm not going to feel embarrassed (much) for posting my function, but the alternative RegEx and WinAPI solutions offered below are
clearly the better approaches. Thank you all!
Jacques.