I know I'm late from the party now 5 and a half years later, but someone might find it useful, as I've found my way here too.
Method 1: NumberFormat
double value = 1234.5678;
NumberFormat formatter1 = new DecimalFormat("##.0");
String text1 = formatter1.format(value); // "1234.6"
NumberFormat formatter2 = new DecimalFormat("##.00");
String text2 = formatter2.format(value); // "1234.57"
Rounding approach is optionally configurable:
formatter.setRoundingMode(RoundingMode.CEILING);
// UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY
Using this, we can modify the code a little bit to achieve the desired behavior:
double value = 127.12;
NumberFormat formatter = new DecimalFormat("##.00");
formatter.setRoundingMode(RoundingMode.FLOOR);
String output = (value == (int) value)
? Double.toString(value)
: formatter.format(value);
This meets your requirements. One thing to mention, for 123.4 it returns 123.40. If you'd like to prevent this, we can do the integer comparison with a shifted decimal dot:
double value = 127.12;
NumberFormat formatter = new DecimalFormat("##.00");
formatter.setRoundingMode(RoundingMode.FLOOR);
String output = (value * 10 == (int) (value * 10))
? Double.toString(value)
: formatter.format(value);
This returns "127.0" for 127.000000, "0.0" for 0.000000, "123.45" for 123.456 and also "123.4" for 123.4.
Method 2: Simple Java
It's not the nicest way, but maybe the shortest? Previously I just did:
double value = 1234.56789;
String text = Double.toString(Math.round(value * 10.0) / 10.0); // "1234.6"
Same with keeping at most 2 digits:
double value = 1234.56789;
String text = Double.toString(Math.round(value * 100.0) / 100.0); // "1234.57"
This way we explicitly round the number to a desired precision. We can truncate it too:
double value = 1234.56789;
String text = Double.toString(((int) (value * 10.0) / 10.0)); // "1234.5"
One could argue, that making a multiplication and a division is a waste of computational power, but I guess it's still faster than modifying the result string, removing trailing zeros, etc. Also, since floating points are stored in memory in binary format and not decimal, running * 10.0 / 10.0 might not result the exact same number.
int(result) - result == 0givesfalsefor result = 127.00000f? It should be true.