3

I need to write currency values like $35.40 (thirty five dollars and forty cents) and after that, i want to write some "****"

so at the end it will be: thirty five dollars and forty cents********* in a maximun of 100 characters

I've asked a question about something very likely but I couldn't understand the main command.

String format = String.format("%%-%ds", 100);
String valorPorExtenso = String.format(format, new Extenso(tituloTO.getValor()).toString());

What do I need to change on format to put *** at the end of my sentence? The way it is now it puts spaces.

skaffman
  • 381,978
  • 94
  • 789
  • 754
Gondim
  • 2,760
  • 7
  • 39
  • 59

5 Answers5

2

I would do:

String line = "thirty five dollars and forty cents";
StringBuilder lineBuffer = new StringBuilder(line);
for(int i=0; i < 100 - line.length(); i++){
    lineBuffer.append("*");
}
line = lineBuffer.toString();
morja
  • 7,779
  • 2
  • 31
  • 51
2

You may want to look at commons-lang http://commons.apache.org/lang/api-release/index.html

I'm under the impression that you want to pad this out to 100 characters.

http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#rightPad%28java.lang.String,%20int,%20java.lang.String%29

The other option is to create a base string of 100 '*' characters.

Create a string builder and do the following:

StringBuilder sb= new StringBuilder(new Extenso(tituloTO.getValor()).toString());
sb.append(STARS_STR);
String val= sb.substring(0, 100);

That should get out the value formatted out.

Dave G
  • 9,152
  • 33
  • 40
1

Short answer, you can't pad with anything other than spaces using String.format. Either use apache StringUtils or write a snippet of code to do it yourself, there is an answer here http://www.rgagnon.com/javadetails/java-0448.html

Nick Fortescue
  • 40,193
  • 23
  • 99
  • 131
1

This formatting will give you 100 characters including your string

String.format("%-100s", "thirty five dollars and forty cents.").replaceAll("  ", "**");

UPDATE :

String.format("%-100s", "thirty five dollars and forty cents.").replaceAll("  ", "**").replace("* ", "**");
niksvp
  • 5,425
  • 2
  • 22
  • 40
  • 1
    beware, this will not work correctly if you have an uneven number of spaces at the end of the string. – morja Jan 07 '11 at 12:24
  • the resulting string will have a length of 100 but if there is an uneven number of spaces, the last char will be a space – Redlab Jan 07 '11 at 13:00
  • @morja and Redlab - I thing pringlesinn was not keen to get exact 100 characters trimming trailing space. But still if you want it please check and comment on the update. – niksvp Jan 10 '11 at 07:19
0

You can't with String.format(), there are however utils to do it in apache's StringUtils. Or just write little method that append the * for your specified length.

Redlab
  • 2,784
  • 16
  • 17