android kotlin 小数保留格式化位数

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
    }
posted @   烟花易冷心易碎  阅读(106)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· DeepSeek本地性能调优
· autohue.js:让你的图片和背景融为一体,绝了!
· 10亿数据,如何做迁移?
点击右上角即可分享
微信分享提示