0

What I want to do is getting the first 2 digits of a number. If number hasn't digits more than 1 then It will add leading zeros.

s variable equals to "122" but I want to get first 2 digits which are "12". I think there is a problem with my format.

for example if totalNumberOfCars equals 6 then s variable will equals to "06".

int totalNumberOfCars = 122;
String s = String.format("%02d", (totalNumberOfCars + 1))

EDIT: Is there anyone knows what String.format("%02d", totalNumberOfCars) does?

2
  • why are you writing this one : (totalNumberOfCars + 1)? Commented Aug 20, 2013 at 11:54
  • @codeMan I edited. It is not important actually. Commented Aug 20, 2013 at 11:56

3 Answers 3

2

I'm afraid that String.format() won't do the job, see http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax.

But your format string will be a good starting point for a substring since any ifs are unnecessary:

int totalNumberOfCars = 122;
String s = String.format("%02d", (totalNumberOfCars + 1));
s = s.substring(0,2);

By the way the condensed explaination from the javadoc link above:

The format specifiers which do not correspond to arguments have the following syntax:

  %[flags][width]conversion

[...] further down on the same page:

Flags '0' [...] [means] zero-padded

[...] further down on the same page:

Width

The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.

Example output would be:

1  --> 01
-1 --> -1
10 --> 10
122--> 122
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe not very elegant, but it should work:

String s = ((totalNumberOfCars<10?"0":"")+totalNumberOfCars).substring(0,2);

Comments

-1

String s = substring_safe (s, 0, 2);

static String substring_safe (String s, int start, int len) { ... } which will check lengths beforehand and act accordingly (either return smaller string or pad with spaces).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.