Search code examples
kotlinformattingdoubledecimaldecimalformat

Kotlin/Java formatting Double values


My current formatting is this

DecimalFormat("#,##0.00").format(value)

I need to handle values like this

0.00 //ok
0.45 //ok
0.002 //Need to show 0.002 or 0.0020
0.0003 //Need to show 0.0003 or 0.00030
0.00004 //Need to show 0.00004 or 0.000040
0.00234567 //Need to show 0.0023

But sure the above code will not work on fractional part where a non zero value started at thousandth place else I will just ended up displaying 0.00 as if it is totally a zero value. I still want the above formatting with comma when dealing with whole number but also allowing me to format when non zero starts beyond hundredths place.

Further sample

0.0492 // 0.04 or 0.05 much better
700.356 // 700.35 or 700.36 much better
54232.542234 // 54,232.54

Solution

  • Try multiplying the number by 10 until you know you got to two non zero digits. This way you will get the number of decimal points you have to round up.

    After that you use the NumberFormat to format the number like this:

    val format = NumberFormat.getInstance()
    format.maximumFractionDigits = nrOfDecimalPoints
    val formattedNumber = format.format(yourNumber)
    

    This way you will keep the thousands separator "," and the decimal will be cut off after two non zero digits.

    EDIT

    This is how the custom function looks like:

    private fun customFormat(number: Double): String{
        var temp = number - number.toInt()
        temp *= 100
        var nrDec = 2
        if (number <= 0.0){
            return "0.00"
        }
        if (temp >= 1.0){
            val format = NumberFormat.getInstance(Locale.US)
            format.maximumFractionDigits = nrDec
            return format.format(number)
        }
        while (temp < 1.0 && nrDec < 15){
            temp *= 10
            nrDec ++
        }
        if((temp * 10 % 10) != 0.0){
            nrDec++
        }
        val format = NumberFormat.getInstance(Locale.US)
        format.maximumFractionDigits = nrDec
        return format.format(number)
    }