在处理价格时保留AppleScript中的小数点

时间:2012-03-01 22:06:23

标签: applescript

我有一个巨大的文本文件,每行的价格都嵌入了15个字符的字符串中。

实施例:     1856年 0200 8751285

在上面的示例中,价格为$ 2.00

我提取价格没问题。我正在使用Satimage脚本添加 向AppleScript添加正则表达式功能 并使用代码:

set findPrice to find text "[0-9]{15}" in theString with regexp, string result and all occurrences
set findPrice2 to characters 5 thru 8 of item 1 of findPrice as string
set findPrice3 to findPrice2 * 0.01

上面代码的结果是我总是得到一个没有的数字 如果价格是整数,则为小数位。但我需要包括所有价格 美分(或精度为2)。

如何让AppleScript以2美元的格式输出2美元的价格? 此外,我不能围绕价格,所以我不能使用圆形命令。

3 个答案:

答案 0 :(得分:0)

此处有一个format_number例程:http://www.j-schell.de/node/153 - 这比您需要的更多,因为它还会插入数千个分隔符等,但您可以“按原样”使用它,或者也许将它减少到你需要的小数位数功能。它也适用于不同的语言环境等。

答案 1 :(得分:0)

试试这个......

set startPrices to quoted form of POSIX path of ("" & (path to desktop) & "prices.txt")
set endPrices to do shell script "grep -E [0-9]{15} " & startPrices & " | sed -e s'/^....\\(....\\)......./\\1/' -e s'/^0/$/' -e s'/^[0-9]/$&/' -e s'/..$/.&/'"

答案 2 :(得分:0)

为避免过于冗长,您可以在获取文本片段时手动将小数点放在那里,或者您可以使用printf格式化您的字符串(这也可以摆脱前导零) ,例如

set findPrice to "185602008751285"
tell findPrice to set findPrice2 to text 5 thru 8
set findPrice3 to (do shell script "printf '%.2f' " & (findPrice2 * 0.01))
相关问题