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!
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!
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");
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