How to use java.String.format in Scala?

Asked

Viewed 465 times

3

I’m trying to use the method .format string. But if I put %1, %2, etc. in the string, the java.util exception.Unknownformatconversionexception is released, pointing to a confusing Java code:

private void checkText(String s) {

    int idx;

    // If there are any '%' in the given string, we got a bad format
    // specifier.
    if ((idx = s.indexOf('%')) != -1) {
        char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
        throw new UnknownFormatConversionException(String.valueOf(c));
    }
}

I conclude that the character % is prohibited. If so, what I should use as arguments to be replaced?

I use Scala 2.8.

  • 2

    Daniel, you explicitly mentioned version 2.8 of Scala. But the best way to "Format" Strings in Scala came with interpolation in version 2.10. For anyone interested: link to the documentation.

1 answer

2

You do not need to use numbers to indicate position. By default, the argument position is simply the order in which it appears in the string.

Here’s an example of how to use this:

String result = String.format("O método format é %s!", "legal");
// resultado igual a "O método format é legal!".

You’ll always wear one % followed by some other character so that the method knows how to show the string. %s is usually the most common, and means that the argument should be treated as string.

Some examples to give an idea:

// podemos especificar o # de decimais para um número de ponto flutuante:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// "10 / 3 = 3.33"

// separador de milhar:
result = String.format("O elefante pesa %,d gramas.", 1000000);
// result now equals  "O elefante pesa 1,000,000 gramas."

String.format uses a java.util.Formatter. For full documentation, see Formatter javadocs.

  • Breaking my head watching a tutorial, now that I realize that for us is comma and not point rs, vlw man

Browser other questions tagged

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