android kotlin 小數保留格式化位數

烟花易冷心易碎發表於2024-06-05

import java.math.RoundingMode
import java.text.NumberFormat
import java.util.*

/**

  • 支援設定舍入模式的型別小數
    */
    inline fun Any?.formatDecimalRoundingMode(
    decimalDigits: Int = 2,
    roundingMode: RoundingMode = RoundingMode.HALF_UP,
    failValue: Double = 0.0
    ): String {
    val numberFormat = NumberFormat.getNumberInstance(Locale.getDefault())
    numberFormat.roundingMode = roundingMode
    numberFormat.maximumFractionDigits = decimalDigits
    return try {
    numberFormat.format(this?.toString()?.toDouble())
    .formatDecimalInterruptOrFillMode(decimalDigits)
    } catch (e: NumberFormatException) {
    numberFormat.format(failValue).formatDecimalInterruptOrFillMode(decimalDigits)
    }
    }

/**

  • 強模式小數格式化,超長的直接擷取,長度不夠填充0
    */
    inline fun Any?.formatDecimalInterruptOrFillMode(
    decimalPlaces: Int = 2,
    failValue: Double = 0.0
    ): String = try {
    String.format("%.\({decimalPlaces}f", this.toString().toDouble()) } catch (e: NumberFormatException) { String.format("%.\){decimalPlaces}f", failValue)
    }

/**

  • 強模式小數格式化,超長的直接擷取,長度不夠填充0
    */
    inline fun Any?.formatDecimal(
    failValue: Double = 0.0
    ): Double = try {
    toString().toDouble()
    } catch (e: NumberFormatException) {
    failValue
    }

相關文章