1

Applescript を使用して数字に 3 桁ごとの区切り記号 (コンマ) を入れようとして、非常にクレイジーな時間を過ごしています。おそらくうまくいくと思われる 2 つのサブルーチンをネット上で見つけましたが、何もうまくいっていないようです。

それは私にあらゆる種類のランダムなフォーマットを与えています。整数から実数、短整数、文字列などに変更しようとしましたが、何も役に立たないようです。

私が渡しているもの:

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

呼び出し:

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

サブルーチン: (明らかに、これらの両方が必要です)

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
4

2 に答える 2

1

最も簡単なのは、do シェル スクリプトを使用して複雑な perl 呼び出しを使用することです。

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 は、このようなテキスト処理には適していません。(最初に printF を使用しようとしましたが、do シェル スクリプト呼び出し用のロケールが設定されていません。)

于 2014-08-05T19:22:27.577 に答える