处理数量、单价、金额之间的计算

This commit is contained in:
zxj
2025-07-11 09:46:08 +08:00
parent 32bc730a21
commit f92ae70423
10 changed files with 98 additions and 79 deletions
@@ -7,7 +7,8 @@ import kotlin.math.pow
fun Float.toFormattedString(decimalPlaces: Int = 2): String {
return when (this) {
0f -> ""
else -> "%.${decimalPlaces}f".format(this)
else -> "%.${decimalPlaces}f".format(this) // 先格式化为固定位数
// .replace(Regex("\\.?0+$"), "") // 移除末尾的0
}
}
@@ -15,6 +16,7 @@ fun Double.toFormattedString(decimalPlaces: Int = 2): String {
return when (this) {
0.0 -> ""
else -> "%.${decimalPlaces}f".format(this)
// .replace(Regex("\\.?0+$"), "")
}
}
@@ -29,9 +29,10 @@ fun String.isNumeric(): Boolean {
return this.matches("-?\\d+(\\.\\d+)?".toRegex())
}
fun String.toFormattedString(decimalPlaces: Int = 2): String {
fun String?.toFormattedString(decimalPlaces: Int = 2): String {
return when (this) {
else -> "%.${decimalPlaces}f".format(this)
null -> ""
else -> "%.${decimalPlaces}s".format(this)
}
}
@@ -73,7 +74,14 @@ fun String.toSafeDouble(): Double {
fun String.isValidFloat(): Boolean {
if (startsWith(".")) return false
val decimalRegex = Regex("^\\d*\\.?\\d{0,2}$")
// 处理前导零的情况
if (length > 1 && startsWith("0")) {
// 允许 "0" 和 "0.x" 但不允许 "00", "01", "00.1" 等
if (!startsWith("0.")) {
return false
}
}
val decimalRegex = Regex("^\\d+\\.?\\d{0,2}$")
return this.matches(decimalRegex)
// return input.matches(Regex("-?\\d+(\\.\\d+)?"))
}