-1

I was trying to format the String "2%" using the following code String.format("s%2", 2) and I got java.util.UnknownFormatConversionException: Conversion = 'End of String'.

So with the above result commes the questing how can I add '%' as a member of the output on the String

2
  • 1
    The Javadoc should help here. If I remember correctly you need to escape % by doubling. Also the conversion needs to start with a % so try"%s%%". Commented Nov 10, 2020 at 8:30
  • Check this answer here: stackoverflow.com/a/77988364/9133569 Commented Feb 13, 2024 at 13:41

2 Answers 2

2

You represent a literal % by doubling it up...put %%.

To print "2%", where the 2 comes from the integer passed in as an argument to the format() call, you want this:

String str = String.format("%d%%", 2);

System.out.println(str);

Result:

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

Comments

0

You need to escape unwanted %. Otherwise String will take it as arguments. To escape single percent sign you need to add another percent character behind it ie. %%.

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.