I have following numbers : 1, 2, 3, 4, 10
But I want to print those numbers like this:
0001
0002
0003
0004
0010
I have searched in Google. the keyword is number format. But I've got nothing, I just get, format decimal such ass 1,000,000.00
. I hope you can suggest me a reference or give me something to solve this problem.
Thanks
Edit,
we can use NumberFormat, or String.format("%4d", somevalue); but it just for adding 0
character before integer. How If I wanna use character such as x
, #
or maybe whitespace
.
So the character become:
xxxx1
xxx10
or ####1
###10
or 1####
10###
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String.
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.
Format string XXX is not a valid format string so it should not be passed to String.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string.
NumberFormat nf = new DecimalFormat("0000");
System.out.println(nf.format(10));
This prints "0010".
Take a look at this
What you want to do is "Pad" your result.
e.g. String.format("%04d", myValue)
;
You can use String.format();
public static String addLeadingZeroes(int size, int value)
{
return String.format("%0"+size+"d", value);
}
So in your situation:
System.out.println(addLeadingZeroes(4, 75));
prints
0075
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