105 lines
2.7 KiB
Kotlin
105 lines
2.7 KiB
Kotlin
package com.sw.inbound.ext
|
|
|
|
import java.math.BigDecimal
|
|
import java.math.RoundingMode
|
|
import kotlin.math.pow
|
|
import kotlin.math.round
|
|
|
|
fun Float.toFormattedString(decimalPlaces: Int = 2): String {
|
|
return when (this) {
|
|
0f -> ""
|
|
else -> "%.${decimalPlaces}f".format(this) // 先格式化为固定位数
|
|
// .replace(Regex("\\.?0+$"), "") // 移除末尾的0
|
|
}
|
|
}
|
|
|
|
fun Double.toFormattedString(decimalPlaces: Int = 2): String {
|
|
return when (this) {
|
|
0.0 -> ""
|
|
else -> "%.${decimalPlaces}f".format(this)
|
|
// .replace(Regex("\\.?0+$"), "")
|
|
}
|
|
}
|
|
|
|
fun Double.toSafeBigDecimal(): BigDecimal {
|
|
return when (this) {
|
|
0.0 -> BigDecimal(0)
|
|
else -> toBigDecimal()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 保留指定小数位数
|
|
*/
|
|
private fun Double.roundToDouble(decimalPlaces: Int): Double {
|
|
val factor = 10.0.pow(decimalPlaces)
|
|
return round(this * factor) / factor
|
|
}
|
|
|
|
private fun Float.roundToDouble(decimalPlaces: Int): Double {
|
|
val factor = 10.0.pow(decimalPlaces)
|
|
return round(this * factor) / factor
|
|
}
|
|
|
|
fun Float?.toSafeString(unitName: String?): String {
|
|
if (this == null || this == 0f) return ""
|
|
val decimalPlaces = getDecimalPlaces(unitName)
|
|
return "%.${decimalPlaces}f".format(this)
|
|
}
|
|
|
|
fun Double?.toSafeString(unitName: String?): String {
|
|
if (this == null || this == 0.0) return ""
|
|
val decimalPlaces = getDecimalPlaces(unitName)
|
|
return "%.${decimalPlaces}f".format(this)
|
|
}
|
|
|
|
fun Double?.toSafeDouble(unitName: String?): Double {
|
|
if (this == null || this == 0.0) return 0.0
|
|
|
|
val decimalPlaces = getDecimalPlaces(unitName)
|
|
return roundToDouble(decimalPlaces)
|
|
}
|
|
|
|
fun Double?.toSafeDouble(decimalPlaces: Int = 2): Double {
|
|
if (this == null || this == 0.0) return 0.0
|
|
|
|
return roundToDouble(decimalPlaces)
|
|
}
|
|
|
|
fun Double?.toSafeFloat(unitName: String?): Float {
|
|
if (this == null || this == 0.0) return 0f
|
|
|
|
val decimalPlaces = getDecimalPlaces(unitName)
|
|
return roundToDouble(decimalPlaces).toFloat()
|
|
}
|
|
|
|
fun Double?.toSafeFloat(decimalPlaces: Int = 2): Float {
|
|
if (this == null || this == 0.0) return 0f
|
|
|
|
return roundToDouble(decimalPlaces).toFloat()
|
|
}
|
|
|
|
fun Float?.toSafeFloat(decimalPlaces: Int = 2): Float {
|
|
if (this == null || this == 0f) return 0f
|
|
|
|
return roundToDouble(decimalPlaces).toFloat()
|
|
}
|
|
|
|
/**
|
|
* 通过单位判断小数
|
|
*/
|
|
private fun getDecimalPlaces(unitName: String?): Int {
|
|
val decimalPlaces = when (unitName) {
|
|
"斤", "公斤", "升", "千克" -> 2
|
|
else -> 0
|
|
}
|
|
return decimalPlaces
|
|
}
|
|
|
|
fun BigDecimal.toFormattedString(): String {
|
|
return this.setScale(2, RoundingMode.HALF_UP).toString()
|
|
}
|
|
|
|
fun Int.toFormattedString(): String {
|
|
return this.toString()
|
|
} |