I created these functions that work well to create a US dollar format:
function Round(Number, Digits, Multiples) -- rounds number with decimal places (ex: round(1.2345, 3) == 1.235)
local Num = Number * 10 ^ Digits
Num = Num>=0 and math.floor(Num+0.5) or math.ceil(Num-0.5) -- rounds (including negatives)
Num = Num / (10 ^ Digits)
if Multiples then Num = math.round(Num / Multiples) * Multiples end -- ex: in the case of 90 degrees, providing -173 rounds to -180
return Num
end
function CurrencyFormat(Value)
local Sign = Value < 0 and '-' or ''
Value = Round(math.abs(Value), 2) -- remove the sign (if negative) and round to 2 decimal places
Value = tostring(Value)
Value = Value:reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")
Value = Sign .. "$ " .. Value
if not string.find(Value, ".", 1, true) then
Value = Value .. ".00"
elseif string.sub(string.sub(Value, -2), 1, 1) == "." then -- if it has only 1 decimal digit (.7)
Value = Value .. "0"
end
return Value
end
print(CurrencyFormat(-1234.5678))
print(CurrencyFormat(321.9))
print(CurrencyFormat(1))
Some results:
-$ 1,234.57
$ 321.90
$ 1.00
But, as I said, currently it is only for USD.
I am now wanting to internationalize this currency format, for any country, and we have many variations as in this table:
Is there any SIMPLE way to do these location-based format conversions?