0

How can I make a float value to only show the dot and the decimals if they exist. For example show 17 instead of 17.0 but if I have a 17.2 show the dot and the decimals.

Thanks!

Genis
  • 37
  • 1
  • 2
  • 7
  • 5
    http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0/14126736#14126736 – Egor Neliuba Dec 18 '13 at 13:29

2 Answers2

0

You might also require to limit the length of fraction part, because there might a result like 12.00001 after a sequence of floating point operations. Code snippet I use to nicely format a double to a string:

private static final DecimalFormat[] formats= new DecimalFormat[]{
    null,
    new DecimalFormat("#.#"),
    new DecimalFormat("#.##"),
    new DecimalFormat("#.###"),
    new DecimalFormat("#.####")
};

public static String toConciseString(double d, int fractionLength){
    long asLong = (long) d;
    if(Math.abs(d - asLong) < 0.00001d){
        return Long.toString(asLong);
    }

    return formats[fractionLength].format(d);
}

Test cases showing the output examples:

assertThat(toConciseString(23.323, 2)).isEqualTo("23.32");
assertThat(toConciseString(23.329, 2)).isEqualTo("23.33");
assertThat(toConciseString(23.329, 3)).isEqualTo("23.329");
assertThat(toConciseString(23.3, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.30001, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.00001, 2)).isEqualTo("23");
Andrey Chaschev
  • 15,055
  • 5
  • 43
  • 63
0

Try this:

    DecimalFormat decimalFormat = new DecimalFormat("#0.##");
    float float1 = 1.00f;
    float float2 = 1.02f;
    System.out.println(decimalFormat.format(float1));
    System.out.println(decimalFormat.format(float2));

It will print out:

1
1.02
Pieter
  • 898
  • 11
  • 22