2

I need a string like 50 to appear as 050.0. I am using String.format, but I can't figure out how to do leading zeros and a single decimal place at the same time. So far, I have tried String.format("%3.2f", number);, but that isn't working as I still get 50.0 rather than 050.0

Cole Smith
  • 23
  • 3

2 Answers2

2

Use DecimalFormat to control the number of mandatory digits:

DecimalFormat df = new DecimalFormat("#000.0");
System.out.println(df.format(50)); // 050.0

where

Symbol  Location    Localized?  Meaning
0       Number      Yes         Digit
#       Number      Yes         Digit, zero shows as absent
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

You can use StringBuilder class to create a string with number 0 and then append it with you number and insert the decimals at the end.

 int num = 50; /*Your number*/
 StringBuilder s_num = new StringBuilder("0"); 
 s_num.append(num); 
 s_num.append(".0");
 String f_num = s_num.toString();