How to format a String with other elements using format()

Asked

Viewed 1,031 times

4

I would like to know how to format a String 08041995 on 08/04/1995 using the Java format() method

    PrintStream ps = new PrintStream(arq);
    String valor = "250,35";
    ps.format("R$ "+"%s", valor);
    ps.flush();

I was able to insert a String (R$) at the beginning of the String (value), but insert elements in a String, such as bars... I don’t know.

How to do it? Thanks!

1 answer

2

You won’t be able to use the String.format for this, but you can break the string into 3 parts (using substring) for such:

String valor = "08041995";
String formatado = valor.substring(0, 2) + "/" +
                   valor.substring(2, 4) + "/" +
                   valor.substring(4, 8);
  • It would be even better if you created a custom formatter by extending the java.text.Format class to encapsulate the logic of this conversion within it and reuse it within your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.