2

Declaring a variable of this form %.2f what I want is to have maximum 2 digits after decimal point.

As it is now, it shows only two as expected, I would like to have also the trailing zeros removed.

formatString = "< %.2f Km"

where I use formatString as String.format(formatString , value)

Is there a way to do it during this part of the code?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • https://stackoverflow.com/questions/48804787/is-there-a-better-way-to-convert-a-double-to-its-exact-decimal-string/48804879#48804879 – Yati Sawhney Jun 05 '18 at 15:14
  • [Remove trailing zero in Java](//stackoverflow.com/q/14984664) – 001 Jun 05 '18 at 15:15
  • Possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](https://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – 0x1C1B Jun 05 '18 at 15:22

1 Answers1

1

This should work for your case:

double value = 3.502;
String formatString = "< %s Km";
String formattedString = String.format(formatString, new DecimalFormat("#.##").format(value));

Duplicate of How to nicely format floating numbers to String without unnecessary decimal 0?

0x1C1B
  • 1,204
  • 11
  • 40
  • I've tested it, it keeps integer without `.`, it removes trailing `0` after the 1st decimal. I think it is the perfect solution for the question. – KeitelDOG Jun 05 '18 at 16:22
  • Wouldn’t this be much cleaner as simply `new DecimalFormat("< #.## Km").format(value)`, without using String.format at all? – VGR Jun 05 '18 at 16:35
  • maybe I'm doing something wrong, but in my case it still shows one 0 after whole numbers. e.g.: `100` is shown `100.0`. I would like to show whole numbers if they are like that. here is a snippet with my code: https://pastebin.com/RuxZPdDv , first is where is declared and the second one where it is returned – Leo Messi Jun 06 '18 at 15:19
  • @LeoMessi If you use `new DecimalFormat("#.##")` instead of `new DecimalFormat(".##")`, it should also work for whole numbers – 0x1C1B Jun 06 '18 at 17:19