Number Formatting in Java

1. Overview

In this tutorial, we’ll look at different approaches to number formatting in Java and how to implement them.

2. Basic Number Formatting with String#format

The String#format method is very useful for formatting numbers. The method takes two arguments. The first argument describes the pattern on how many decimals places we want to see, and the second argument is the given value:

double value = 4.2352989244d;
assertThat(String.format("%.2f", value)).isEqualTo("4.24");
assertThat(String.format("%.3f", value)).isEqualTo("4.235");

3. Decimal Formatting by Rounding

In Java, we have two primitive types that represent decimal numbers – float and decimal:

double myDouble = 7.8723d;
float myFloat = 7.8723f;

The number of decimal places can be different depending on the operations being performed. In most cases, we’re only interested in the first couple of decimal places. Let’s take a look at some ways to format a decimal by rounding.

3.1. Using BigDecimal for Number Formatting

The BigDecimal class provides methods to round to a specified number of decimal places. Let’s create a helper method that will return a double, rounded to a desired number of places:

public static double withBigDecimal(double value, int places) {
    BigDecimal bigDecimal = new BigDecimal(value);
    bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
    return bigDecimal.doubleValue();
}

We start with a new instance of BigDecimal with our original decimal value. Then, by setting the scale, we provide the number of decimal places we want and how we want to round our number. Using this method allows us to easily format a double value:

double D = 4.2352989244d;
assertThat(withBigDecimal(D, 2)).isEqualTo(4.24);
assertThat(withBigDecimal(D, 3)).isEqualTo(4.235);

3.2. Using Math#round

We can also take advantage of the static methods in the Math class to round a double value to a specified decimal place. In this case, we can adjust the number of decimal places by multiplying and later dividing by 10^n. Let’s check our helper method:

public static double withMathRound(double value, int places) {
    double scale = Math.pow(10, places);
    return Math.round(value * scale) / scale;
}
assertThat(withMathRound(D, 2)).isEqualTo(4.24);
assertThat(withMathRound(D, 3)).isEqualTo(4.235);

However, this way is only recommended in particular cases as sometimes output might be rounded differently as it was expected before it’s printed.

This is because Math#round is truncating the value. Let’s see how this can happen:

System.out.println(withMathRound(1000.0d, 17));
// Gives: 92.23372036854776 !!
System.out.println(withMathRound(260.775d, 2));
// Gives: 260.77 instead of expected 260.78

And so, the method is only listed for learning purposes.

4. Formatting Different Types of Numbers

In some particular cases, we may want to format a number for a specific type like currency, large integer, or percentage.

4.1. Formatting Large Integers With Commas

Whenever we have a large integer in our application, we may want to display it with commas, by using DecimalFormat with a predefined pattern:

public static String withLargeIntegers(double value) {
    DecimalFormat df = new DecimalFormat("###,###,###");
    return df.format(value);
}

int value = 123456789;
assertThat(withLargeIntegers(value)).isEqualTo("123,456,789");

4.2. Padding a Number

In some cases, we may want to pad a number with zeros for a specified length. Here, we can use the String#format method, as described earlier:

public static String byPaddingZeros(int value, int paddingLength) {
    return String.format("%0" + paddingLength + "d", value);
}

int value = 1;
assertThat(byPaddingOutZeros(value, 3)).isEqualTo("001");

4.3. Formatting Numbers With Two Zeros After the Decimal

To be able to print any given number with two zeros after the decimal point, we’ll use one more time DecimalFormat class with a predefined pattern:

public static double withTwoDecimalPlaces(double value) {
    DecimalFormat df = new DecimalFormat("#.00");
    return new Double(df.format(value));
}

int value = 12; 
assertThat(withTwoDecimalPlaces(value)).isEqualTo(12.00);

In this case, we’ve created a new format with a pattern specifying two zeros after the decimal point.

4.4. Formatting and Percentages

From time to time we might need to display percentages.

In this case, we can use the NumberFormat#getPercentInstance method. This method allows us to provide a Locale to print the value in a format that is correct for the country you specified:

public static String forPercentages(double value, Locale locale) {
    NumberFormat nf = NumberFormat.getPercentInstance(locale);
    return nf.format(value);
}

double value = 25f / 100f;
assertThat(forPercentages(value, new Locale("en", "US"))).isEqualTo("25%");

4.5. Currency Number Formatting

A common way to store currencies in our application is by using the BigDecimal. What if we want to display them to the user? In this case, we can use the NumberFormat class:

public static String currencyWithChosenLocalisation(double value, Locale locale) {
    NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
    return nf.format(value);
}

We get the currency instance for a given Locale and then simply call the format method with the value. The result is the number displayed as currency for the specified country:

double value = 23_500;
assertThat(currencyWithChosenLocalisation(value, new Locale("en", "US"))).isEqualTo("$23,500.00");
assertThat(currencyWithChosenLocalisation(value, new Locale("zh", "CN"))).isEqualTo("¥23,500.00");
assertThat(currencyWithChosenLocalisation(value, new Locale("pl", "PL"))).isEqualTo("23 500 zł");

5. Advanced Formatting Use-Cases

DecimalFormat is one of the most popular ways to format a decimal number in Java. Similar to previous examples we’ll write a helper method:

public static double withDecimalFormatLocal(double value) {
    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
    return new Double(df.format(value));
}

Our type of formatting will get the default setting for a given localization.

The decimal formatting is handled differently in different countries using their numeric systems. For example the grouping character (comma in the US, but space or dot in other locales), the grouping size (three in the US and most locales, but different in India), or the decimal character (dot in the US, but a comma in other locales).

double D = 4.2352989244d;
assertThat(withDecimalFormatLocal(D)).isEqualTo(4.235);

We can also extend this functionality to provide some specific patterns:

public static double withDecimalFormatPattern(double value, int places) {
    DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00");
    DecimalFormat df3 = new DecimalFormat("#,###,###,##0.000");
    if (places == 2)
        return new Double(df2.format(value));
    else if (places == 3)
        return new Double(df3.format(value));
    else
        throw new IllegalArgumentException();
}

assertThat(withDecimalFormatPattern(D, 2)).isEqualTo(4.24); 
assertThat(withDecimalFormatPattern(D, 3)).isEqualTo(4.235);

Here we allow our user to configure DecimalFormat by chosen pattern based on the number of spaces.

6. Conclusion

In this article, we briefly went through different ways of number formatting in Java. As we can see there is no one best way to do this. Many approaches might be followed as each of them has its own characteristics.

As always, the code for these examples is available over on GitHub.

Related posts:

Java Program to Check whether Directed Graph is Connected using DFS
Java Program to Implement vector
Java Program to Implement Park-Miller Random Number Generation Algorithm
Biểu thức Lambda trong Java 8 – Lambda Expressions
Hướng dẫn Java Design Pattern – Proxy
Spring WebClient Requests with Parameters
Encode a String to UTF-8 in Java
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Finding the Differences Between Two Lists in Java
Spring Security OAuth2 – Simple Token Revocation
Java InputStream to String
Enum trong java
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Spring Boot - Admin Client
Java Program to Implement Pagoda
Apache Commons Collections MapUtils
Custom Cascading in Spring Data MongoDB
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Class Loaders in Java
Guide to @ConfigurationProperties in Spring Boot
Java Program to Perform Insertion in a BST
Java Program to Implement Shunting Yard Algorithm
The HttpMediaTypeNotAcceptableException in Spring MVC
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Hướng dẫn Java Design Pattern – Memento
Annotation trong Java 8
Spring Cloud Series – The Gateway Pattern
Spring Boot: Customize the Jackson ObjectMapper
Hướng dẫn Java Design Pattern – Adapter
Exploring the Spring Boot TestRestTemplate