Home > Software design >  How to format a float so that the digit before the separator is not shown, if it is 0
How to format a float so that the digit before the separator is not shown, if it is 0

Time:03-30

I currently something like this:

float someFloat = -0.42f;
String.format("%.2f", someFloat);

This will print as:

-0.42

I would like to save space, since this is output to a GUI with limited horizontal space. So instead I would like it to print:

-.42

and similarly for a positive value, e.g.:

.52

For values a with |a|>1, it should still print the digit before the separator, e.g.:

42.42

How do I achieve this?

CodePudding user response:

You can use DecimalFormat instead, this works for greater than 1 value as well

float someFloat = -0.42f;
String withoutLeadingZero = new DecimalFormat(".##").format(someFloat);
System.out.println(withoutLeadingZero);
  • Related