package com.sw.inbound.ext import java.math.BigDecimal import java.math.RoundingMode fun String.isValidAmount(): Boolean { // 空字符串允许(用于删除所有字符) if (this.isEmpty()) return true // 检查是否只包含数字和小数点 if (!matches(Regex("^\\d*\\.?\\d*$"))) return false // 检查小数点数量(最多一个) if (count { it == '.' } > 1) return false // 检查小数点后位数(最多2位) if (contains('.')) { val decimalPart = substringAfter('.') if (decimalPart.length > 2) return false } // 检查不以小数点开头 if (startsWith('.')) return false return true } fun String.isNumeric(): Boolean { return this.matches("-?\\d+(\\.\\d+)?".toRegex()) } fun String.toFormattedString(decimalPlaces: Int = 2): String { return when (this) { else -> "%.${decimalPlaces}f".format(this) } } fun String.toSafeBigDecimal( scale: Int = 2, roundingMode: RoundingMode = RoundingMode.HALF_UP ): BigDecimal { return when { this.isBlank() -> BigDecimal.ZERO.setScale(scale, roundingMode) this == "." -> BigDecimal.ZERO.setScale(scale, roundingMode) else -> try { BigDecimal(this.trim()) .setScale(scale, roundingMode) } catch (e: Exception) { BigDecimal.ZERO.setScale(scale, roundingMode) } } } fun String.isValidNumber(): Boolean { return matches(Regex("^\\d*$")) } fun String.toSafeInt(): Int { return if (this.isEmpty()) { 0 } else { this.toInt() } } fun String.toSafeDouble(): Double { return if (this.isEmpty()) { 0.0 } else { this.toDouble() } } fun String.isValidFloat(): Boolean { if (startsWith(".")) return false val decimalRegex = Regex("^\\d*\\.?\\d{0,2}$") return this.matches(decimalRegex) // return input.matches(Regex("-?\\d+(\\.\\d+)?")) } fun String.toSafeFloat(maxDecimalDigits: Int = 2): Float { return if (this.isEmpty()) { 0f } else if (isValidFloat()) { toFloat() } else { 0f } }