如何使用AppleScript让Calculator.app自动选择显示的小数位数
macOS计算器自动调整小数位数AppleScript方案
功能说明
- 支持手动键入、粘贴两种输入场景的自动小数位数匹配
- 兼容粘贴时末尾0被自动截断的问题,可强制保留原始输入的小数位数
- 支持0-15位小数范围的自动调整
完整代码
-- 获取剪贴板中原始数字的小数位数(解决粘贴丢末尾0问题) on getClipboardDecimalCount() try set cbContent to the clipboard as string if cbContent contains "." then set decimalPart to text ((offset of "." in cbContent) + 1) thru -1 of cbContent return length of decimalPart else return 0 end if on error return -1 end try end getClipboardDecimalCount -- 获取计算器当前显示值的小数位数 on getCalcDisplayDecimalCount() tell application "Calculator" set displayValue to display value as string if displayValue contains "." then set decimalPart to text ((offset of "." in displayValue) + 1) thru -1 of displayValue return length of decimalPart else return 0 end if end tell end getCalcDisplayDecimalCount -- 调整计算器小数显示位数 on setCalcDecimalPlace(placeNum) if placeNum < 0 or placeNum > 15 then return tell application "System Events" to tell process "Calculator" set menuItemName to placeNum as string click menu item menuItemName of menu 1 of menu item "小数位数" of menu 1 of menu item "显示" of menu bar 1 end tell end setCalcDecimalPlace -- 主逻辑 set cbDecimalCount to getClipboardDecimalCount() if cbDecimalCount ≥ 0 then -- 优先用剪贴板原始位数(适配粘贴场景) set targetCount to cbDecimalCount else -- 无有效剪贴板数字时用计算器显示值的位数(适配手动输入场景) set targetCount to getCalcDisplayDecimalCount() end if if targetCount > 15 then set targetCount to 15 setCalcDecimalPlace(targetCount)
使用方法
手动触发版(推荐,资源占用低)
- 打开「自动操作.app」,新建「快速操作」
- 顶部选项设置:工作流收到「没有输入」,位置选择「Calculator.app」
- 左侧动作库搜索「运行AppleScript」,拖入右侧编辑区,替换默认代码为上面的脚本
- 保存动作,命名为「自动调整计算器小数位数」
- 打开「系统设置 > 键盘 > 快捷键 > 服务」,找到刚才保存的动作,绑定快捷键即可,每次输入完成后按快捷键自动调整
全自动触发版
如果不需要手动按快捷键,可以在脚本外层添加常驻循环逻辑,保存为应用后设置开机自启即可:
on idle if application "Calculator" is running then -- 此处插入上文完整主逻辑代码即可 end if return 0.5 -- 每0.5秒检查一次输入状态 end idle
粘贴末尾0丢失问题说明
Calculator.app默认粘贴数值时会自动截断末尾无意义的0,导致显示位数少于原始输入。上述脚本优先读取剪贴板内的原始字符串计算小数位数,调整后会强制计算器显示对应位数的小数,自动补全被截断的末尾0,即可解决粘贴12.30仅显示12.3的问题。
内容的提问来源于stack exchange,提问作者sebseb
相关产品推荐
相关产品推荐

