0

So I use ...

System.out.printf("%.2f",variable);

and it works. But if the second decimal place is a 0, it just ignores the zero and gives the answer to one decimal place. How can I get two decimal places including the zero?

Thanks.

001
  • 13,291
  • 5
  • 35
  • 66
Boone9
  • 11
  • 2
    Does this answer your question? [Java - always keep two decimal places even in zeroes](https://stackoverflow.com/questions/20463196/java-always-keep-two-decimal-places-even-in-zeroes) – Matt U Jan 24 '22 at 17:44
  • 1
    Can't reproduce: https://ideone.com/OPSVhm. Can you make a [mre]? – 001 Jan 24 '22 at 17:49
  • `%.2f` should work. ["For the floating-point conversions 'a', 'A', 'e', 'E', and 'f' the precision is the number of digits after the radix point."](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html) – Andy Thomas Jan 24 '22 at 17:50
  • 'System.out.printf("%.2f",2.0000); ' does print '2.00' as expected. Se running code here: https://github.com/RobbingDaHood/answers/blob/master/so70838166/src/Main.java – RobbingDaHood Jan 24 '22 at 17:55

1 Answers1

0

you can use DecimalFormat like this

DecimalFormat decimalFormat = new DecimalFormat("#0.00");
String format = decimalFormat.format(variable);