2 回答
TA贡献1828条经验 获得超3个赞
首先,我需要说的是,没有明确格式的通用提议函数的方法没有意义,因为像@gidds和@DodgyCodeException注释一样,它容易受到歧义的影响。
因此,我使用按逗号分组的小数点分隔符和倒置情况(按点分组的逗号分隔符)来解决。然后清理逗号并替换点,以便获得我要解析为的无分组点十进制格式regex[0-9]+(,[0-9]{3})*\\.[0-9]{2}[0-9]+(\\.[0-9]{3})*,[0-9]{2}Double
我这样做的方式是:extension function
const val NOTHING = ""
const val COMMA = ","
const val POINT = "."
val commaGrouped = "[0-9]+(,[0-9]{3})*\\.[0-9]{2}".toRegex()
val pointGrouped = "[0-9]+(\\.[0-9]{3})*,[0-9]{2}".toRegex()
fun String.commaCleaned() = replace(COMMA, NOTHING)
fun String.pointCleaned() = replace(POINT, NOTHING)
fun String.commaToPoint() = replace(COMMA, POINT)
fun String.pointToComma() = replace(POINT, COMMA)
fun String.toDouble() =
when {
commaGrouped matches this -> Double(commaCleaned())
pointGrouped matches this -> Double(pointCleaned().commaToPoint())
else -> throw IllegalArgumentException(
"the value ${this} can't be converted to ${Double::class.java} " +
"have match ${commaGrouped.pattern} " +
"or ${pointGrouped.pattern}")
}
意识到整数格式或超过两个小数精度将不匹配以创建 ,这也是我想要的。Double
添加回答
举报