String.format() to format double in Java
Use String.format("%.2f", number)
to format a double to a String in Java. This rounds the number to two decimal places.
This gives you "123.46"
, a neat String representation of your double.
Want to include a thousands separator? Use String.format("%1$,.2f", number)
:
You get "123,456.79"
— with a ,
as the thousands separator.
Code breakdown and custom separators
Demystifying the format pattern
Let's dissect our pattern "%1$,.2f"
:
%1$
points to the first argument.,
inserts a thousands separator..2
limits output to two decimal places.f
ensures a floating-point representation.
Custom decimal and grouping separators
Encountered a scenario asking for a custom decimal or grouping separator? Time to invoke DecimalFormat
and DecimalFormatSymbols
:
Voilà! We're using a space as the grouping separator and a dot for decimals, giving you "123 456.79"
.
Locale-specific formatting
Your project may demand locale-specific formatting. Trust NumberFormat
:
Above, we format following French locale conventions. That's locale handling à la Java!
Practical use-cases
There are plenty of contexts where tailored number formatting shines:
Finance
Invoices and financial reports call for stringent number formatting. Tools like String.format
and DecimalFormat
enforce consistency.
International applications
For global software, locale-sensitive formatting is non-negotiable for clear communication.
Data science
When visualizing data in charts or graphs, precision in decimal places enhances clarity for your audience.
GUI development
Numbers in UIs should honor user expectations and locale conventions—easily handled with Java's formatting utilities.
Was this article helpful?