Files
StallDualScreen/app/src/main/java/com/sw/dualscreen/utils/RemoveZeroUtils.kt
T

67 lines
2.0 KiB
Kotlin

package com.sw.dualscreen.utils
import java.math.RoundingMode
import java.text.DecimalFormat
import kotlin.text.contains
import kotlin.text.format
import kotlin.text.replace
/**
* 去除小数点后无效零的工具类
* 功能示例:
* 1230.00 => 1230
* 1230.10 => 1230.1
* 3.40 => 3.4
* 3.0 => 3
*/
class RemoveZeroUtils {
companion object {
/**
* 方法1:使用字符串格式化(最简单)
* @param number 输入的double数值
* @return 去除无效零后的字符串
*/
fun removeZeroByFormat(number: Double): String {
return "%.10f".format(number) // 先格式化为固定小数位
.replace(Regex("0*$"), "") // 移除末尾的零
.replace(Regex("\\.$"), "") // 如果小数点后全为零,移除小数点
}
/**
* 方法2:使用DecimalFormat(推荐)
* @param number 输入的double数值
* @return 去除无效零后的字符串
*/
fun removeZeroByDecimalFormat(number: Double): String {
val format = DecimalFormat("0.##########")
format.roundingMode = RoundingMode.FLOOR
return format.format(number)
}
/**
* 方法3:使用正则表达式处理字符串
* @param number 输入的double数值
* @return 去除无效零后的字符串
*/
fun removeZeroByRegex(number: Double): String {
var str = number.toString()
// 如果包含小数点,处理末尾的零
if (str.contains(".")) {
str = str.replace(Regex("0+?$"), "") // 移除末尾的零
.replace(Regex("[.]$"), "") // 如果小数点后全为零,移除小数点
}
return str
}
}
}
// 扩展函数方式,更符合Kotlin风格
fun Double?.removeTrailingZeros(): String {
if (this == null) return ""
return RemoveZeroUtils.removeZeroByDecimalFormat(this)
}