0

i am trying to format a string as follows

System.out.println("unique number is :"+ number[b]);
System.out.println("unique number formatted to 28  is :"+ String.format("%-28s",number[b]).replace(' ','0'))

there is no issue when "number" is a string that is shorter than 28, it adds the 0's to the left, but when the string is longer than 28 it dosnt shorten it, am i doing anything wrong ?

its an extract from a loop BTW

Many thanks

1
  • 1
    how do you want it shortend? Shortening numbers by cutting of digits normally doesn't make sense. Commented Apr 9, 2013 at 7:55

2 Answers 2

1

The formatter doesn't cut your String, it only makes sure it uses at least 28 spaces.

You would have to do something like:

if (str.length() > 28) {
    str = str.subString(0, 28);
}

or maybe

if (str.length() > 28) {
    str = str.subString(str.length() - 28, str.length());
}

to limit the size.

Sign up to request clarification or add additional context in comments.

Comments

0

The reason that format is not working as you expect is clear from the javadoc for the java.util.Formatter class. It says:

"The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output."

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.