简体   繁体   中英

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). A found a lot of solutions that work for positive numbers but none that work for negative. 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.

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 . 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]
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM