Bitwise DEVS
Bitwise DEVS

Reputation: 3489

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

Upvotes: 1

Views: 2627

Answers (2)

UrbanR
UrbanR

Reputation: 202

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

Upvotes: 2

LenglBoy
LenglBoy

Reputation: 331

You can do it like this in order to cut of tailing 0:

public static void main(String []args){
    double number1 = 0.2;
    double number2 = 1.55;
    double number3 = 0.00005;
    double number4 = 0.50000;
    
    DecimalFormat df = new DecimalFormat("###,##0.00#########");
    System.out.println(df.format(number1)); // 0.20
    System.out.println(df.format(number2)); // 1.55
    System.out.println(df.format(number3)); // 0.00005
    System.out.println(df.format(number4)); // 0.50
 }

You just need to know how far your decimal digits should be checked.

Upvotes: 1

Related Questions