Posted at

Cocoaの機能を使って3桁区切り文字列や価格文字列と数字を変換するAppleScriptハンドラ

More than 1 year has passed since last update.



  • numberFormatは第1引数のクラスによって返り値が変わる


    • 文字列を引数にすると、数字を返す

    • 数字を引数にすると、文字列を返す




  • convertNumberStyleの第2、第3引数はハンドラ名の文字列


numberFormat.scpt

use scripting additions

use framework "Foundation"

log (my decimalNumberFormat:"1,234,567") as integer
--> 1234567

log (my japanesePriceFormat:1234567) as text
--> "1,234,567円"

log my convertNumberStyle("1,234,567円", "japanesePriceFormat:", "yenSignFormat:") as text
--> "¥1,234,567"

log my convertNumberStyle("¥1,234,567", "yenSignFormat:", "decimalNumberFormat:") as text
--> "1,234,567"

on decimalNumberFormat:num
--require framework: Foundation
set numberFormatter to current application's NSNumberFormatter's alloc()'s init()
set numberFormatter's numberStyle to current application's NSNumberFormatterDecimalStyle as integer
return my numberFormat(num, numberFormatter)
end decimalNumberFormat:

on japanesePriceFormat:num
--require framework: Foundation
set numberFormatter to current application's NSNumberFormatter's alloc()'s init()
set numberFormatter's positiveFormat to "#,##0円"
return my numberFormat(num, numberFormatter)
end japanesePriceFormat:

on yenSignFormat:num
--require framework: Foundation
set numberFormatter to current application's NSNumberFormatter's alloc()'s init()
set numberFormatter's numberStyle to current application's NSNumberFormatterCurrencyStyle as integer
set numberFormatter's currencyCode to "JPY"
return my numberFormat(num, numberFormatter)
end yenSignFormat:

on numberFormat(num, numberFormatter)
if class of (num as anything) is in {number, integer, real} then
return numberFormatter's stringFromNumber:num
else if class of (num as anything) is in {text, string} then
return numberFormatter's numberFromString:num
else
error "Invalid argument"
end if
end numberFormat

on convertNumberStyle(numberString, originalNumberFormatSelector, styleNumberFormatSelector)
--require framework: Foundation
if not (my respondsToSelector:originalNumberFormatSelector) then
error "Invalid handler: " & originalNumberFormatSelector
end if
set num to my performSelector:originalNumberFormatSelector withObject:numberString
if not (my respondsToSelector:styleNumberFormatSelector) then
error "Invalid handler: " & styleNumberFormatSelector
end if
return my performSelector:styleNumberFormatSelector withObject:num
end convertNumberStyle



更新履歴


  • 2018-08-19: NSNumberFormatterクラスを使って新規作成

  • 2018-08-21: japanesePriceFormatyenSignFormatを作成

  • 2018-09-01: numberFormatconvertNumberStyleを作成