Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Number Formatting in Java

$
0
0

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.


Viewing all articles
Browse latest Browse all 4535

Trending Articles