Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please ..

How do I formate in Java ??

Such as setw () in C++
Posted

NumberFormat is what you are searching for:

Formatting in Java[^]
 
Share this answer
 
I usually use the static method String.format() for that. If you are familiar with the C printf() you can use this immediately because it works the same way.
Example:
String formatted = String.format("name: %-20s age: %10d", nameString, ageInt);

In the above example the width of name will be at least 20 characters and the width of age will be 10 characters, padded with spaces if needed. The '-' character means that if the width of nameString is less than 20 characters then we want to aling it to the left side.

EDIT: Just tried out that you can use %s for any type, java performs the conversion to string. Still, you might want to use %d or %f if you want for example zero prefix padding for integers %09d or want to specify the precision for floats: %10.3f
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900