LiveCode function to insert commas to separate number into groups

Back To LiveCode Main Page

I looked for a formatting command to format my numbers as ###,###,### but did not find one. So I wrote a function named iComma (for insert Comma). I put it here to share it with the public (and to remind me not to reinvent the wheel)


function iComma n
#Insert Commas into numbers
put len (n) into nlen --Get the number of digits in number to format

if nlen < 4 then return n -- If there is less than four digits, return the number, do not format it.

repeat with i=nlen to 1 step -1 -- Start loop; looping backwards, from the number of digits down to one.
add 1 to c -- Keep count to know when to insert comma
put char i of n before tmp -- Build new formatted number, one digit at a time, working right to left.
if c = 3 then -- If count is 3 then …
put "," before tmp -- …insert a comma
put 0 into c -- reset count to zero
end if
end
repeat -- end the loop

if first char in tmp is "," then -- test if there is a comma leading the number
delete first char in tmp -- remove leading comma
end if

return tmp -- return the newly formatted number with the inserted commas.

end iComma


To use the function just call it with a statement like the following.

on mouseUp pMouseButton
-- An example of how the function can be used return a formatted line count in be displayed in a field.
put number of lines in field "textView" into tmp -- put the number of lines into a variable named tmp
put iComma (tmp) into field "lineCount" -- call function iComma to insert commas into the number
-- ...and place the formatted number into field "lineCount"
end mouseUp




Tested with LiveCode 9.0 in Linux Mint 18 (Sarah)