hellzone
hellzone

Reputation: 5236

java string format method

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?

Upvotes: 0

Views: 1426

Answers (3)

daus
daus

Reputation: 396

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

Upvotes: 2

trogdor
trogdor

Reputation: 1656

Maybe not very elegant, but it should work:

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

Upvotes: 0

user2692684
user2692684

Reputation: 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).

Upvotes: -1

Related Questions