Java
String.format
double formatting
Java programming
code examples

String.format to format double in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Overview

In Java, the String.format() method is a powerful tool used for formatting strings, including formatting numbers, dates, and text. When dealing with floating-point numbers, such as double in Java, String.format() is highly efficient in presenting numeric data in a human-readable format.

Basic Usage of String.format() with Double

The basic syntax for String.format() is as follows:

java
String.format(String format, Object... args)

The format string contains plain text and format specifiers. Format specifiers start with a % character and are followed by optional argument index, flags, width, precision, and conversion characters.

Example

Format a double value to 2 decimal places:

java
double value = 123.456789;
String formattedString = String.format("%.2f", value);
System.out.println(formattedString); // Output: 123.46

Explanation

  • %: Indicates the start of the format specifier.
  • .2: Specifies the precision, which means two digits after the decimal point.
  • f: Stands for floating-point number.

Formatting Specifiers

General Syntax

  • %[argument_index$][flags][width][.precision]conversion

Conversion Characters

CharacterDescription
fFormats the argument as a decimal number (fixed-point).
eFormats the number in scientific notation (exponential).
gUses f or e, whichever is more compact.

Flags

Flags can modify the formatting of numbers:

FlagDescription
-Left-justify within the given width.
+Forces to show the + or - sign for numeric values.
0Zero-padded output.
,Includes locale-specific grouping separators (e.g., thousands).

Width and Precision

  • Width: Minimum number of characters to output. If the formatted value is smaller than the width, spaces are added.
  • Precision: Number of digits after the decimal point for floating-point numbers.

Example with Width and Flag

java
double value = 12345.6789;
String formattedString = String.format("%,10.2f", value);
System.out.println(formattedString); // Output: "  12,345.68"
  • 10 dictates a minimum width of 10 characters.
  • , adds a comma separator.
  • Spaces are padded to reach the width if needed.

Scientific Notation

To format a double in scientific notation, the %e specifier can be used:

java
double value = 12345.6789;
String formattedString = String.format("%.3e", value);
System.out.println(formattedString); // Output: "1.235e+04"

Explanation

  • .3e: Formats the number in scientific notation with three digits of precision.

Using Locale for Formatting

Java allows for locale-specific formatting, which can be crucial for applications where the number format needs to adhere to a specific cultural format.

java
1import java.util.Locale;
2
3double value = 12345.6789;
4String formattedString = String.format(Locale.GERMANY, "%,.2f", value);
5System.out.println(formattedString); // Output: "12.345,68" (Colon as decimal separator in German)

Table: Summary of Key Points

AspectDescription
Basic SyntaxString.format(String format, Object... args)
%fFixed-point number format.
Width & PrecisionFormat specifier determines output width and decimal places.
Scientific Notation%e formats numbers in scientific notation.
Locale SupportFormats numerics according to the specified Locale.
FlagsModify number formatting (e.g., sign, zero-padding).

Additional Tips

  1. Always specify the precision: This influences how the number appears, especially for floating-point numbers where precision might vary.
  2. Be cautious with large numbers: Be mindful of the inclusion of grouping separators or scientific notation when working with extremely large or small numbers.
  3. Consider rounding behavior: Java's representation of floating-point numbers can exhibit rounding errors. Using String.format() can help mitigate some display concerns.

The String.format() method in Java is essential for developers needing precise control over the output appearance of floating-point numbers, providing a comprehensive range of formatting options. Whether it involves establishing a consistent presentation or adhering to locale-specific conventions, String.format() offers a versatile solution for double value formatting.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.