Rekijan Kileren
Rekijan Kileren

Reputation: 313

Show decimal of a double only when needed (rounding issue)

I am trying to get a desired output based on a variable input. I can get close to what I want but there seems to be an issue with rounding a number.

What I want by example (input > output).

30 > 30
30.0 > 30
30.5 > 30,5
30.5555 > 30,6
30.04 > 30

The problem is that the last one comes back as 30.0. Now I understand why this is happening (because of the rounding up/down)

My code:

private String getDistanceString(double distance) {
        distance = 30.55;
        DecimalFormat df = new DecimalFormat(".#");
        if (distance == Math.floor(distance)) {
            //If value after the decimal point is 0 change the formatting
            df = new DecimalFormat("#");
        }
        return (df.format(distance) + " km").replace(".", ",");
    }

Upvotes: 3

Views: 368

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65793

It is almost always wrong to use == with floating point numbers. You should use Math.abs(a - b) < x.

private String getDistanceString(double distance) {
    DecimalFormat df = new DecimalFormat(".#");
    if (Math.abs(distance - Math.round(distance)) < 0.1d) {
        //If value after the decimal point is 0 change the formatting
        df = new DecimalFormat("#");
    }
    return (df.format(distance) + " km").replace(".", ",");
}

public void test() {
    double[] test = {30d, 30.0d, 30.5d, 30.5555d, 30.04d, 1d / 3d};
    for (double d : test) {
        System.out.println("getDistanceString(" + d + ") = " + getDistanceString(d));
    }
}

Upvotes: 2

nafas
nafas

Reputation: 5423

A hack around it, is to replace with regex

return 
       (""+df.format(distance))
       .replaceAll("\\.(0+$)?", ",") //replace . and trailing 0 with comma,
       .replaceAll(",$","") //if comma is last char, delete it
       + " km"; //and km to the string

Upvotes: 0

Related Questions