Jun 22, 2017

Add comma separators to large numbers

It was hard to read a column of large numbers, so here's a function to add the commas. It is implemented in liveCode.


// make big integers readable by adding commas 
function addCommas z delim
  -- 4567 -> 4,567
  -- TTD make for for floats
  -- include option for european or other delimiter "."
  if delim is empty then put "," into delim
  put the number of chars of z into N
  put trunc((N - .01) / 3) into numCommas
  if numCommas > 0 then
    repeat with j = 1 to numCommas
      put delim before char (N - (j*3) + 1) of word 1 of z
    end repeat
  end if
  return z    -- z has been modified to contain commas
end addCommas

Use:

put addCommas(11456789)

Returns:

11,456,789

Long example:

on mouseUp
  put "" into fld "out1"
  repeat with i = 1 to 20
    put fibonacciNumber(i+31) into n  -- make big numbers
    put addCommas(n) into line i of fld out1
  end repeat
end mouseUp

// Returns the number at 1-based index pIndex >= 2 in the Fibonacci sequence
function fibonacciNumber pIndex
  local tFirst = 1, tSecond = 1
  local tCounter, tSum
  repeat with tCounter = 3 to pIndex
     put tFirst + tSecond into tSum
     put tSecond into tFirst
     put tSum into tSecond
  end repeat
  return tSecond
end fibonacciNumber

// make big integers readable by adding commas 
function addCommas z delim
  -- 4567 -> 4,567
  -- TTD make for for floats
  -- include option for european or other delimiter "."
  if delim is empty then put "," into delim
  put the number of chars of z into N
  put trunc((N - .01) / 3) into numCommas
  if numCommas > 0 then
    repeat with j = 1 to numCommas
      put delim before char (N - (j*3) + 1) of word 1 of z
    end repeat
  end if
  return z    -- z has been modified to contain commas
end addCommas

(find in livecode related ds/fibonacci_random_commas.livecode)

No comments: