【问题标题】:Format negative decimal number with extension kotlin使用扩展名 kotlin 格式化负十进制数
【发布时间】:2021-12-27 16:27:58
【问题描述】:

我有一个简单的问题,但我没有找到解决方案。我有很大的负数 ex(-6763.98) 我想要的是这样的 ex($-6.78K)。 A 发现了许多适用于正数的解决方案,但没有一个适用于负数的解决方案。这是我现在拥有的代码。

const val COUNT_DIVISOR = 1000
       const val COUNT_DIVISOR_FLOAT = 1000.0
       fun getFormattedNumber(count: Long): String {
        if (count < COUNT_DIVISOR) return "" + count
        val exp = (ln(count.toDouble()) / ln(COUNT_DIVISOR_FLOAT)).toInt()
        return resources.getString(
            R.string.decimal_format_long_number_price,
            count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble()), EXTENSION[exp - 1]
        )
    }
      

【问题讨论】:

  • 这会有帮助吗? “如果(计数 -1000.0)”

标签: android kotlin string-formatting


【解决方案1】:

natural logarithm 没有为负值定义,因此函数 ln 将返回 NaN(不是数字)用于负输入。

来自lnKotlin documentation

Special cases:
ln(NaN) is NaN
ln(x) is NaN when x < 0.0
ln(+Inf) is +Inf
ln(0.0) is -Inf

您必须确保输入始终为正值才能正确计算指数。

val exp = (ln(abs(count.toDouble())) / ln(COUNT_DIVISOR_FLOAT)).toInt()

另一个问题是第一个if 检查,它为小于COUNT_DIVISOR 的所有输入返回输入值本身。您还必须允许大量的负输入通过那里。

if (count > -COUNT_DIVISOR && count < COUNT_DIVISOR) return "" + count  

大家一起

const val COUNT_DIVISOR = 1000
const val COUNT_DIVISOR_FLOAT = 1000.0

fun getFormattedNumber(count: Long): String {
    if (count > -COUNT_DIVISOR && count < COUNT_DIVISOR) return "" + count
    val exp = (ln(abs(count.toDouble())) / ln(COUNT_DIVISOR_FLOAT)).toInt()
    return resources.getString(
        R.string.decimal_format_long_number_price,
        count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble()), EXTENSION[exp - 1]
    )
}

如果您希望结果始终保留 2 位小数,请考虑其中任何一个

val result = count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble())

// This will use the root language/region neutral locale
// it will use the dot '.' as the decimal separator
"%.2f".format(Locale.ROOT, result)

// This will use the default locale
// it will use '.' or ',' as the decimal separator, based on the user settings on the target system
"%.2f".format(result)

val localeDefinedByYou = ... // or define a specific locale
"%.2f".format(localeDefinedByYou, result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多