[英]Format negative decimal number with extension kotlin
I have a simple problem for which I didn`t find a solution.我有一个简单的问题,但我没有找到解决方案。 I am having large negative number ex(-6763.98) what I want is something like this ex($-6.78K).我有很大的负数 ex(-6763.98) 我想要的是这样的 ex($-6.78K)。 A found a lot of solutions that work for positive numbers but none that work for negative. A 发现了许多适用于正数的解决方案,但没有一个适用于负数的解决方案。 This is the code that I am having right now.这是我现在拥有的代码。
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]
)
}
The natural logarithm is not defined for negative values so the function ln
will return NaN
(not a number) for negative inputs.自然对数没有为负值定义,因此 function ln
将为负输入返回NaN
(不是数字)。
You have to make sure that the input is always a positive value in order to calculate the exponent correctly.您必须确保输入始终为正值才能正确计算指数。
val exp = (ln(abs(count.toDouble())) / ln(COUNT_DIVISOR_FLOAT)).toInt()
Another problem is the first if
check, which returns the input value itself for all inputs smaller than COUNT_DIVISOR
.另一个问题是第一个if
检查,它为小于COUNT_DIVISOR
的所有输入返回输入值本身。 You have to allow large negative inputs through there as well.您还必须允许大量的负输入通过那里。
if (count > -COUNT_DIVISOR && count < COUNT_DIVISOR) return "" + count
All together全部一起
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]
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.