初始代码提交
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package com.sw.inbound
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
// println(4, 2 + 2)
|
||||
val decimalPlaces = 2
|
||||
val r1 = "%.${decimalPlaces}f".format(0.1)
|
||||
logStr("r1", r1)
|
||||
val r2 = "%.${decimalPlaces}f".format(1.0)
|
||||
logStr("r2", r2)
|
||||
val r3 = "%.${decimalPlaces}f".format(1.23)
|
||||
logStr("r3", r3)
|
||||
}
|
||||
|
||||
fun log(tag: String, msg: Boolean) {
|
||||
println("$tag, result = $msg")
|
||||
}
|
||||
|
||||
fun logStr(tag: String, msg: String) {
|
||||
println("$tag, result = $msg")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFloat() {
|
||||
log("0.00", "0.00".isValidFloat())
|
||||
log("0.01", "0.01".isValidFloat())
|
||||
log("00", "00".isValidFloat())
|
||||
log("01", "01".isValidFloat())
|
||||
log("10", "10".isValidFloat())
|
||||
log("10.00", "10.00".isValidFloat())
|
||||
log("10.01", "10.01".isValidFloat())
|
||||
log("10.011", "10.011".isValidFloat())
|
||||
log("0.0-1", "0.0".isValidFloat(1))
|
||||
log("10.011-1", "10.011".isValidFloat(1))
|
||||
log("10.01-1", "10.01".isValidFloat(1))
|
||||
log("10.0-1", "10.0".isValidFloat(1))
|
||||
log("10.0-0", "10.0".isValidFloat(0))
|
||||
log("10.01-0", "10.01".isValidFloat(0))
|
||||
}
|
||||
|
||||
fun String.isValidFloat(maxFractionDigits: Int = 2): Boolean {
|
||||
if (isEmpty()) return false
|
||||
if (startsWith(".")) return false
|
||||
|
||||
// 处理前导零的情况
|
||||
if (length > 1 && startsWith("0")) {
|
||||
// 允许 "0" 和 "0.x" 但不允许 "00", "01", "00.1" 等
|
||||
if (!startsWith("0.")) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 构建动态正则表达式
|
||||
val decimalRegex = when {
|
||||
maxFractionDigits <= 0 -> Regex("^\\d+$") // 不允许小数
|
||||
else -> Regex("^\\d+\\.?\\d{0,${maxFractionDigits}}$")
|
||||
}
|
||||
|
||||
return matches(decimalRegex)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user