JavaRush /Java Blog /Random EN /Formatting Number Output in Java

Formatting Number Output in Java

Published in the Random EN group
Hi all! Often, numbers come into our methods that need to be displayed in some special format. It seems like a small thing, but how would you implement this task? Formatting Number Output in Java - 1Let's think about this for a bit today. First, to dive head first into Java number formatting, let's recall the format method of the String class : public static String format(String format, Object… args) - returns a string formatted from the format string with the rest of the args . And just an example:
String str = String.format("Hi - %s! How are you %s?", "Sasha", "At work");
As a result, we will get the output in the console:
Hello Sasha! How are things at work?

printf and format methods

String.format() is not the only method for formatting a string. Its counterparts are System.out.printf() and System.out.format(); . So, we can replace the previous code with:
System.out.printf("Hi - %s! How are you %s?", "Sasha", "At work");
System.out.format("Hi - %s! How are you %s?", "Sasha", "At work");
The output in the console will remain the same. The only difference is that these methods immediately print the value to the console, unlike String.format() . But I like String.format() better because we don't always need to print the result to the console, so we'll use that method later on. Let's return to our example. What do we see? And the fact that in places where there were symbols - %s , lines are inserted - "Sasha" and "at work". How can this help us in development? Imagine that you have a large template text, but in some places you need to insert values ​​that can be different and come as arguments from outside. This is where this formatting comes in handy. Format specifiers begin with a percent sign % and end with a character indicating the type of argument to be formatted. And, as you probably understood, %s is used to insert objects - strings. But if we try to insert, for example, a double in the place where the string object is registered:
String str = String.format("Hi - %s! How are you %s?", 55.6, "At work");
this will also work. double will be cast to a string, and we get:
Hello - 55.6! How are things at work?
Besides strings and floating point numbers, there are other types in Java, right? So let's take a look at the whole arsenal:
The type of value being formatted Example
%s Any type that will be cast to a string
String.format("Hi %s!","world")
Hello World!
%b Any type that will be cast to boolean : true if the value is not null, false if null
String.format("Hi %b!",null)
hello false
%h You can pass any object that will be cast to the hexadecimal string of the value from the hashCode() method
String.format("Hi %h!","world")
Hello 106c44!
%c Used to set a Unicode character ( char )
String.format("Hello m%cr!",'And')
Hello World!
%d Specifies an integer ( int. byte, short, int, long, BigInteger )
String.format("I'm already %d!",20)
I'm already 20!
%f Used to set a floating point number
String.format("PI is - %f!", 3.14159)
The number PI is - 3.141590!
%e Floating point numbers in scientific notation
String.format("PI is - %e!", 3.14159);
The PI number is - 3.141590e+00!
%a Floating point numbers will be represented in hexadecimal
String.format("PI is - %a!", 3.14159)
The PI number is - 0x1.921f9f01b866ep1!
%x An integer ( int. byte, short, int, long, BigInteger ) is passed, the result of formatting will be the character with the given number in the ASCII table
String.format("I'm already %x!",25)
I'm already 19!
%o An integer is accepted ( int. byte, short, int, long, BigInteger ), which will be represented as an octal number
String.format("I already %o!",25);
I'm already 31!
%t Prefix for date and time conversions. Formatting requires additional flags
String.format("Today is %tA",new Date())
Today is Saturday
%n Platform-specific line separator. Analog \n
String.format("Hello %n Hello")
Hi Hi
Let's use a more appropriate format for double :
String str = String.format("The distance from Kyiv to Odessa is %f. Not so short, is it?", 475.4d);
Console output:
The distance from Kyiv to Odessa is 475.400000. Not so little, is it?
As you already understood, %f would be a more appropriate specifier for floating point numbers, which include data types such as double and float in Java. With this specifier, we can format a floating point number:
String str = String.format("The distance from Kyiv to Odessa is %.2f. Not so short, is it?", 475.4d);
Inserting .2 into this specifier will truncate the number of decimal places to two, and we get the output:
The distance from Kyiv to Odessa is 475.40. Not so little, is it?
.2 is not the only subset of specifiers. The combination of these subtunings is called an instruction . Formatting Number Output in Java - 2The general form of the instruction is as follows:
%[argument_index][flags][width][.precision]type specifier
And now let's decipher everything in order:
  • [argument_index] is an integer indicating the position in the list of arguments. For example, a reference to the first argument is $1, a reference to the second argument is $2, and so on. If no position has been given, the arguments must be in the same order as they are referenced in the format string.
  • [flags] - special characters for formatting. For example:
    • + flag meaning that if the numeric value is positive, it must include the + sign
    • - means left alignment of the result
    • , sets the thousands separator for integers
  • [width] is a positive integer decimal number that specifies the minimum number of characters to be printed. If this number is preceded by 0, then the missing characters will be padded with 0, if there is no 0, then spaces.
  • [.precision] is a non-negative integer with a dot in front of it. Typically used to limit the number of characters. The specific behavior depends on the particular type of specifier.
I would also like to note that all of the above elements of the instructions are optional, and everything will work without them. As an example of using subtuning, let's say we want a specific output of pi:
String str = String.format("%1$+09.5f", 3.1415926535897);
And accordingly, the output in the console:
Seems easy, right? But when it comes to number formatting, you can't ignore DecimalFormat . Let's see what is meant.


DecimalFormat is a class for formatting any number in Java, be it an integer or a floating point number. When the DecimalFormat object is created , you can set the formatting template for the incoming numbers directly in the constructor. How our example would look like using DecimalFormat :
DecimalFormat dF = new DecimalFormat( "#.###" );
double value = 72.224463;
Console output:
The string #.### is a pattern that indicates that we are formatting the passed value to 3 decimal places. What other symbols are available for templates? Here are some of them:
  • # is a digit, leading zeros are omitted;
  • 0 - the digit is always displayed, even if the number has fewer digits (in this case, 0 is displayed);
  • . - decimal separator sign;
  • , is a separator grouping sign (for example, thousands separator);
  • ; - separate formats;
  • - - marks the prefix of a negative number;
  • % - multiplies by 100 and shows the number as a percentage;
  • ? - multiplies by 1000 and shows the number in ppm;
  • E - separates mantissa and exponent for exponential format.
Let's take a look at a few examples:
System.out.println(new DecimalFormat( "###,###.##" ).format(74554542.224463));
Console output:
System.out.println(new DecimalFormat( "%###.##" ).format(0.723456));
Console output:
System.out.println(new DecimalFormat( "000.###" ).format(42.224463));
Console output:
It is not necessary to create a new DecimalFormat object each time to define a new template. It will be sufficient to use its applyPattern and applyLocalizedPattern methods :
DecimalFormat dF = new DecimalFormat("###.###");
When we talk about formatting a floating point number, we're talking a lot about rounding, right? So, when truncating a number with decimal places outside the given pattern, DecimalFormat rounds the number up if the last truncated number is greater than 5. And if the last truncated number is 5? Indeed, in this case, this number is exactly in the middle between the nearest integers. Formatting Number Output in Java - 3In this case, the previous number before it is taken into account. If the previous number is even, rounding is done:
DecimalFormat dF = new DecimalFormat("##.###");
String result = dF.format(56.4595);
Console output:
If it is odd, then it is not performed:
DecimalFormat dF = new DecimalFormat("##.###");
String str = dF.format(56.4595);
Console output:
The difference between floating point formatting using String.format() and DecimalFormat.format() is that trailing zeros will be present in the former, even if there is no fractional part. For example:
String firstStr = String.format("%.4f", 9.00001273);
Console output:
DecimalFormat decimalFormat = new DecimalFormat("#.####");
String secondStr = decimalFormat.format(9.00001273);
Console output:
As you can see, when formatting the number 9.00001273 to four decimal places, the format() method of the String class will display the value 9.0000 , while the DecimalFormat format() method will output 9 .

BigDecimal and BigInteger

Since we have touched on such a topic of rounding numbers in Java, let's talk about how to use the BigDecimal class for such operations . This class is geared towards working with really BIG numbers: the maximum double and float values ​​are too small for it. This class has many different settings for floating point rounding, as well as many methods for arithmetic operations. It has a similar class, but focused on working with LARGE integers - BigInteger . You can read more about BigDecimal and BigInteger in this article .

Formatting Date and Time

It was only mentioned above that using the format() of the String class, you can also format the time and date. Formatting Number Output in Java - 4Well, let's take a look at how it's done. First, I would like to remind you that the %t format specifier is used for dates . Second, when formatting a template, each format specifier for dates requires additional formatting flags. Here are the possible formatting flags for dates:
Flags Description
%tB The full name of the month, such as January, February, etc.
%tb Abbreviated name of the month, such as Jan, Feb, etc.
%tA Full name of the day of the week, e.g. Sunday, Monday
%ta Abbreviated name of the day of the week, e.g. Sun, Mon, etc.
%tY Year in 4-digit format, e.g. 0000 to 9999
%ty Year in 2 digit format, e.g. 00 to 99
%tm The month is formatted with zero at the beginning, e.g. 01 to 12
%tc Date and time in the format %ta %tb %td %tT %tZ %tY, for example, Mon Feb 17 03:56:12 PST 2020
%tD Date in the format %tm/%td/%ty
%td Day of the month in two-digit format, for example, 01 to 31
%te Day of the month in the format without leading 0, for example 1 to 31
%tT Time in 24 hour format, e.g. %tH:%tM:%tS
%tH Hour of the day in 24-hour format, from 00 to 23
%tI Hour of the day for 12 hour format, e.g. 01 to 12
%tM Minutes in an hour are formatted from zero at the beginning, for example, from 00 to 59
%tS Seconds in a minute, consisting of two digits, for example, from 00 to 59
%tZ Time zone abbreviation, such as PST, UTC, etc.
This is an abbreviated list of possible date formatting flags - there are a lot of them, for every taste. A complete list of them, as well as possible specifiers, can be found at this link . Let's see how to use it. This time we do not use String.format() , but immediately System.out.printf() .

Example 1

In addition, we set the language of the result by passing it as the first argument to the method:
Date date = new Date();
System.out.printf(Locale.ENGLISH,"%tB %te, %tY",date,date,date);
Console output:
October 11, 2020
Without setting the language, the default language will be used (for example, I have Russian).

Example 2

Let's display a more complete date:
Date date = new Date();
System.out.printf("%td %tB %tY of %n%tH:%tM:%tS",date,date,date,date,date,date,date);
And the output in the console:
October 11, 2020 13:43:22
Passing the same Date object as an argument so many times... Doesn't look very good, does it? Let's use the $ internal subsetting to specify the argument we want to use:
System.out.printf("%1$td %1$tB %1$tY of year %n%1$tH:%1$tM:%1$tS",date);
The output in the console will not change. There are other equally interesting ways to format the date. You can read about them and a little more about time and date in Java in this material . That's all for today, thank you for your attention!Formatting Number Output in Java - 5