0

I have a float number, let's say:

Float number = 2.667f;

String.format("%.1f", number)

will produce:

2,7

but in case of

Float number = 2.0f;

it will produce:

2,0

is it possible to instruct String.format to avoid 0 after comma in case of integer numbers in order to receive for example 2 in the mentioned case.

alexanoid
  • 24,051
  • 54
  • 210
  • 410
  • Check https://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0 , it exactly solves your problem. – Marwa Eldawy Nov 26 '19 at 09:25

1 Answers1

3

You can use DecimalFormat with # symbol:

DecimalFormat df = new DecimalFormat("#.#");
System.out.println(df.format(2.1f)); // 2.1
System.out.println(df.format(2.0f)); // 2
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111