Mule DWL 2.0 实现数字转英文单词的操作方法
DWL 2.0 数字转英文单词实现方案
实现逻辑说明
DWL 2.0 没有内置数字转英文表述的原生函数,我们可以通过自定义递归函数实现常用整数范围的转换,完全适配 123 转为 one hundred and twenty three 的格式要求。
完整实现代码
%dw 2.0 output application/json // 基础数字映射:0-19的特殊英文表述 var singleDigits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] // 整十数字映射:20-90 var tenDigits = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] // 处理小于100的数字转换 fun convertLessThanOneHundred(n: Number) = if (n < 20) singleDigits[n] else ( tenDigits[floor(n / 10)] ++ (if (n mod 10 != 0) (" " ++ singleDigits[n mod 10]) else "") ) // 处理小于1000的数字转换,支持百位后加and规则 fun convertLessThanOneThousand(n: Number) = if (n >= 100) ( singleDigits[floor(n / 100)] ++ " hundred" ++ (if (n mod 100 != 0) (" and " ++ convertLessThanOneHundred(n mod 100)) else "") ) else convertLessThanOneHundred(n) // 主转换函数,支持0-999999范围的整数转换 fun numberToWords(n: Number) = if (n == 0) "zero" else ( var thousands = floor(n / 1000) var remainder = n mod 1000 --- (if (thousands > 0) (convertLessThanOneThousand(thousands) ++ " thousand" ++ (if (remainder > 0 and remainder < 100) " and " else if (remainder >= 100) " " else "")) else "") ++ (if (remainder > 0) convertLessThanOneThousand(remainder) else "") ) --- // 调用示例 numberToWords(123)
测试效果
- 输入
123→ 输出:one hundred and twenty three - 输入
45→ 输出:forty five - 输入
1001→ 输出:one thousand and one - 输入
12345→ 输出:twelve thousand three hundred and forty five
扩展说明
如果需要支持更大范围的数字、小数、负数场景,只需要在现有逻辑基础上新增百万/十亿级的单位映射、小数部分转换规则、负号前缀判断即可。
内容的提问来源于stack exchange,提问作者Karthik Raja J
相关产品推荐
相关产品推荐

