Explain Codes LogoExplain Codes Logo

String.format() to format double in Java

java
formatting
decimal-format
locale-specific-formatting
Anton ShumikhinbyAnton Shumikhin·Sep 2, 2024
TLDR

Use String.format("%.2f", number) to format a double to a String in Java. This rounds the number to two decimal places.

String formatted = String.format("%.2f", 123.456); //Captain, we've rounded off the decimals!

This gives you "123.46", a neat String representation of your double.

Want to include a thousands separator? Use String.format("%1$,.2f", number):

String formatted = String.format("%1$,.2f", 123456.789); //Those commas really weigh a thousand., right?

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:

DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); //Making a point. 🎯 symbols.setGroupingSeparator(' '); //Space: The final frontier. 🚀 DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", symbols); String formatted = decimalFormat.format(123456.789); // We've got some separation anxiety here.

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:

Locale currentLocale = Locale.FRANCE; //Vive la France! 🇫🇷 NumberFormat numberFormat = NumberFormat.getNumberInstance(currentLocale); String formatted = numberFormat.format(123456.789); //Maintenant, nous parlons français! Now, we're speaking French!

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.