Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format String become xxx1, xx10 or 1###, 10## etc

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###

like image 687
trycatch4j Avatar asked May 18 '10 16:05

trycatch4j


People also ask

Does format return a string?

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.

What is the format of 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.

Which of the format string is not valid?

Format string XXX is not a valid format string so it should not be passed to String.

What is D and S in string format?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string.


3 Answers

NumberFormat nf = new DecimalFormat("0000");
System.out.println(nf.format(10));

This prints "0010".

like image 115
Michael Avatar answered Sep 30 '22 09:09

Michael


Take a look at this

What you want to do is "Pad" your result.
e.g. String.format("%04d", myValue);

like image 33
BoxOfNotGoodery Avatar answered Sep 30 '22 09:09

BoxOfNotGoodery


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
like image 42
Martijn Courteaux Avatar answered Sep 30 '22 10:09

Martijn Courteaux