Code: Select all
put 1234567.89 into val
put floor(val) into floored // Get the number w/o the decimals
put val - floored into savedDecimals
if the number of chars in floored >3 then put comma before char -3 of floored
if the number of chars in floored >7 then put comma before char -7 of floored
put char 2 to -1 of savedDecimals after floored
put floored
With an additional line of code you can have it handle numbers larger than 999,999,999, if you're using numbers that big.
It does fail on negative numbers without extra code; that code is in the fuller function below.
I would point out that despite LC's marketing slogan of "less code", in most other languages I can insert commas with a *single* line of code, but because LC lacks backreferences in regular expressions, it takes several lines to do it in LC.
Here's a complete function which adds commas, formats to two decimal places, and handles negative numbers properly.
Code: Select all
put c(1234567.89)
function c val
if char 1 of val is "-" then
put "-" into savedSign
delete char 1 of val
end if
put round(val*100)/100 into val
put floor(val) into floored // Get the number w/o the decimals
put val - floored into savedDecimals
if savedDecimals is 0 then put "0.00" into savedDecimals
else if length(savedDecimals) = 3 then put "0" after savedDecimals
if the number of chars in floored >3 then put comma before char -3 of floored
if the number of chars in floored >7 then put comma before char -7 of floored
put char 2 to -1 of savedDecimals after floored
put savedSign before floored
return floored
end c