excelstringmacosapplescriptapplescript-objc

Add Thousands Separator to Integer - Applescript


I'm having the craziest time trying to get a thousands separator (comma) into my numbers using Applescript. I found two subroutines on the net that supposedly will do the trick, but nothing seems to be going right.

It's giving me all sorts of random formatting. I tried changing up from integer, to real, to small integer, to string, etc. Nothing seems to help.

What I'm passing:

set perCapita2014 to avgHHinc2014 / avgPopHH2014 as integer -- results 17005

The call:

set finalPerCapita2014 to (comma_delimit(perCapita2014)) -- results 0.,0.5

Subroutines: (apparently it requires both of these)

on number_to_string(this_number)
set this_number to this_number as string
if this_number contains "E+" then
    set x to the offset of "." in this_number
    set y to the offset of "+" in this_number
    set z to the offset of "E" in this_number
    set the decimal_adjust to characters (y - (length of this_number)) thru ¬
        -1 of this_number as string as number
    if x is not 0 then
        set the first_part to characters 1 thru (x - 1) of this_number as string
    else
        set the first_part to ""
    end if
    set the second_part to characters (x + 1) thru (z - 1) of this_number as string
    set the converted_number to the first_part
    repeat with i from 1 to the decimal_adjust
        try
            set the converted_number to ¬
                the converted_number & character i of the second_part
        on error
            set the converted_number to the converted_number & "0"
        end try
    end repeat
    return the converted_number
else
    return this_number
end if
end number_to_string

on comma_delimit(this_number)
    set this_number to this_number as string
    if this_number contains "E" then set this_number to number_to_text(this_number)
    set the num_length to the length of this_number
    set the this_number to (the reverse of every character of this_number) as string
    set the new_num to ""
    repeat with i from 1 to the num_length
        if i is the num_length or (i mod 3) is not 0 then
            set the new_num to (character i of this_number & the new_num) as string
        else
            set the new_num to ("," & character i of this_number & the new_num) as string
        end if
    end repeat
    return the new_num
end comma_delimit

Solution

  • Simplest thing is to use a complicated perl call using do shell script:

    set perCapita2014 to (avgHHinc2014 / avgPopHH2014) as integer
    set finalPerCapita2014 to do shell script "echo " & perCapita2014 & " | perl -lpe'1 while s/^([-+]?\\d+)(\\d{3})/$1,$2/'"
    

    Applescript is not good with text crunching like this. (I first tried to use printF, but the locale is not set for do shell script calls.)