Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
static String intToString(int num, int digits) { StringBuffer s = new StringBuffer(digits); int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; for (int i = 0; i < zeroes; i++) { s.append(0); } return s.append(num).toString(); }
Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .
To display numbers with leading zeros in Java, useDecimalFormat("000000000000").
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
In your case it will be:
String formatted = String.format("%03d", num);
Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits); String result = String.format(format, num); return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> % 0 --> 0 %d --> <value of digits> d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With