Some currency formatting regexes for v2
Posted: 28 Jan 2023, 19:10
I always struggle with regular expressions - maybe I'm not alone.
Here are a few regexes to format currency in v2 (US only at the moment, apologies).
(N.B.: The next-to-last two message boxes demonstrate that floats in a MsgBox appear to be formatted incorrectly. Bug? Feature? The last MsgBox is my workaround)
Regards,
burque505
Here are a few regexes to format currency in v2 (US only at the moment, apologies).
Code: Select all
curr := 1000489999.8
newcurr := RegExReplace(curr, "(\d)(?=(\d{3})+(?!\d))", "$1,")
MsgBox(newcurr "`n" "$" newcurr, "Does not ensure two decimal places")
num := 1234567
formattedNumber := RegExReplace(Format("{:.2f}", num), "(\d)(?=(\d{3})+(?!\d))", "$1,")
MsgBox(num "`n" "$" . formattedNumber, "Ensure two decimal places")
num2 := -1234567
formattedNumber2 := (num2 < 0 ? "-" : "") . RegExReplace(Format("{:.2f}", Abs(num2)), "(\d)(?=(\d{3})+(?!\d))", "$1,")
MsgBox(num2 "`n" "$" . formattedNumber2, "Not my favorite ...")
num3 := -12345.88
formattedNumber3 := (num3 < 0 ? "(" : "") . "$" . RegExReplace(Format("{:.2f}", Abs(num3)), "(\d)(?=(\d{3})+(?!\d))", "$1,") . (num3 < 0 ? ")" : "")
MsgBox(num3 "`n" formattedNumber3, "Enclosed in parens")
num4 := -12345.88
formattedNumber4 := (num4 < 0 ? "-" : "") . "$" . RegExReplace(Format("{:.2f}", Abs(num4)), "(\d)(?=(\d{3})+(?!\d))", "$1,")
MsgBox(num4 "`n" formattedNumber4, "Minus sign before")
MsgBox(-12345.88, "Was -12345.88")
MsgBox(12345.88, "Positive 12345.88")
MsgBox(Format("{:.2f}", -12345.67), "Using 'Format' on -12345.67")
Regards,
burque505