【问题标题】:Is there a Kotlin native way to format a float to a number of decimal places?是否有 Kotlin 原生方式将浮点数格式化为小数位数?
【发布时间】:2020-07-28 05:18:34
【问题描述】:

大多数答案都使用 Java(例如 String.format)来完成工作,但我需要一种方法来完全使用 Kotlin 本机来支持多平台编程。

这意味着不使用 Java 包

说一个像 fun Float.toString(numOfDec: Int) 这样的方法。我希望将值四舍五入,例如:

35.229938f.toString(1) 应该返回 35.2

35.899991f.toString(2) 应该返回 35.90

【问题讨论】:

  • 请注意提供替代解决方案的人们...他们需要是 Kotlin Common/JVM/JS/Native...而不是仅适用于 JVM(例如 String.format)。跨度>
  • 这个措辞有点混乱。您所说的“原生 Kotlin”是指“Kotlin Native”吗?
  • 是的...是 glib/不精确...我们正在编写的组件目标/在 iOS 和 Android 上运行

标签: string kotlin floating-point type-conversion representation


【解决方案1】:

我创建了以下 Float 扩展(这也适用于 Double):

/**
 * Return the float receiver as a string display with numOfDec after the decimal (rounded)
 * (e.g. 35.72 with numOfDec = 1 will be 35.7, 35.78 with numOfDec = 2 will be 35.80)
 *
 * @param numOfDec number of decimal places to show (receiver is rounded to that number)
 * @return the String representation of the receiver up to numOfDec decimal places
 */
fun Float.toString(numOfDec: Int): String {
    val integerDigits = this.toInt()
    val floatDigits = ((this - integerDigits) * 10f.pow(numOfDec)).roundToInt()
    return "${integerDigits}.${floatDigits}"
}

【讨论】:

  • 这段代码有问题。考虑 0.01.toString(2),它将返回“0.1”而不是“0.01”,因为删除了小数部分的前导零。
  • 在负值上也会出错; -1.01 -> "-1.-1"
【解决方案2】:

在你的场景中使用它

 try {
            if (!TextUtils.isDigitsOnly(st)) {
                val rounded = Math.round(st.toFloat())
                val toHex = BigInteger(rounded.toString(), 10)
                val t = toHex.toString(16)
                t.toString()
            } else {
                val toHex = BigInteger(st, 10)
                val t = toHex.toString(16)
                t.toString()
            }
        } catch (e: NumberFormatException) {
            error
        }

【讨论】:

  • 如前所述,该解决方案需要使用本机 Kotlin,因为这是针对多平台项目的,因此不能涉及 Java 类/方法/包
【解决方案3】:

如果您想返回一个浮点数,但只删除尾随小数,请使用:

fun Float.roundToDecimals(decimals: Int): Float {
    var dotAt = 1
    repeat(decimals) { dotAt *= 10 }
    val roundedValue = (this * dotAt).roundToInt()
    return (roundedValue / dotAt) + (roundedValue % dotAt).toFloat() / dotAt
}

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 2011-09-15
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多