/*** 提取字符串中的 数字 带小数点 ,没有就返回"0"** @param money* @return*/fun getMoney(money: String): String {var money = moneyvar pattern = Pattern.compile("(\\d+\\.\\d+)")var m = pattern.matcher(money)if (m.find()) {money = if (m.group(1) == null) "0" else m.group(1) as String} else {pattern = Pattern.compile("(\\d+)")m = pattern.matcher(money)money = if (m.find()) {if (m.group(1) == null) "" else m.group(1)} else {"0"}}return money}/*** 汉字转数字* 一零零八六:10086* 一千零四十五:1045*/fun hanZiToArabic(hanziNumber: String): String {val numberMap = mapOf("零" to 0, "一" to 1, "二" to 2, "两" to 2,"三" to 3, "四" to 4, "五" to 5, "六" to 6,"七" to 7, "八" to 8, "九" to 9)val unit = mapOf("万" to 10000, "千" to 1000, "百" to 100,"十" to 10)//包含计数单位var have=falserun loop@{unit.forEach { (s, i) ->have =hanziNumber.contains(s)if(have){return@loop}}}return if(have){//一千零四十五val numbers = mutableListOf<Int>()unit.forEach { (s, i) ->val index = hanziNumber.indexOf(s)if(index!=-1){numberMap[hanziNumber[index-1].toString()]?.let {numbers.add(it * i)}}}numberMap[hanziNumber.last().toString()]?.let {numbers.add(it)//加上个位数}numbers.reduce { acc, i -> acc+i}.toString()//求和}else {//一零零八六var result = ""for (character in hanziNumber) {val number = numberMap[character.toString()]if (number != null) {result += number}}result}}
测试:
public class ExampleUnitTest {@Testpublic void test(){String aa = NumberUtils.INSTANCE.hanZiToArabic("一零五零");System.err.println("一零五零 to "+aa);String aa2 = NumberUtils.INSTANCE.hanZiToArabic("一万五千六十七");System.err.println("一万五千六十七 to "+aa2);}
}
运行结果: