JavaRush /Java Blog /Random EN /Format the output of numbers in Java

Format the output of numbers in Java

Published in the Random EN group
Hi all! Often our methods come with numbers that need to be displayed in some special format. It seems like a small thing, but how would you implement this task? Format the output of numbers in Java - 1We invite you to think about this a little today. First, to dive into number formatting in Java, let's remember the format method of the String class : public static String format(String format, Object... args) - returns a string formatted from the format string using the remaining args arguments . And just an example:
String str = String.format("Hi - %s! How are you %s?", "Sasha", "At work");
System.out.println(str);
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 analogues 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");
or
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 display the value in the console, unlike String.format() . But I like String.format() better, since we don’t always need to display the result in the console, so we will use this method further. Let's return to our example. What do we see? And the fact is that in the places where there were characters - %s , the lines - “Sasha” and “at work” are inserted . 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 understand, %s is used to insert objects - strings. But if we try to insert, for example, a double into 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 will 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 entire arsenal:
Type of value to format Example
%s Any type that will be cast to a string
String.format("Hi %s!","world")
Result:
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)
Result:
Hello false
%h You can pass any object, which will be cast to a hexadecimal value string from the hashCode() method
String.format("Hi %h!","world")
Result:
Hello 106c44!
%c Used to specify a Unicode character ( char )
String.format("Hello m%cr!",'And')
Result:
Hello World!
%d An integer is specified ( int. byte, short, int, long, BigInteger )
String.format("I'm already %d!",20)
Result:
I'm already 20!
%f Used to specify a floating point number
String.format("PI is - %f!", 3.14159)
Result:
The PI number is - 3.141590!
%e Floating point numbers in scientific notation
String.format("PI is - %e!", 3.14159);
Result:
The PI number is - 3.141590e+00!
%a Floating point numbers will be represented in hexadecimal
String.format("PI is - %a!", 3.14159)
Result:
The PI number is - 0x1.921f9f01b866ep1!
%x An integer is passed ( int. byte, short, int, long, BigInteger ), the formatting result will be the character with the given number in the ASCII table
String.format("I'm already %x!",25)
Result:
I'm already 19!
%o An integer ( int. byte, short, int, long, BigInteger ) is accepted and will be represented as an octal number
String.format("I already %o!",25);
Result:
I'm already 31!
%t Prefix for date and time conversions. Additional flags are required for formatting
String.format("Today is %tA",new Date())
Result:
Today is Saturday
%n Platform-specific line separator. Analogue\n
String.format("Hello %n Hello")
Result:
Hi Hi
Let's use a more suitable format for double :
String str = String.format("The distance from Kyiv to Odessa is %f. Not so short, is it?", 475.4d);
System.out.println(str);
Console output:
The distance from Kyiv to Odessa is 475.400000. Not so little, right?
As you may have realized, %f would be a more appropriate specifier for floating point numbers, which include data types like 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, giving us the output:
The distance from Kyiv to Odessa is 475.40. Not so little, right?
.2 is not the only tweak to the specifiers. The combination of these subsettings is called an instruction . Format the output of numbers in Java - 2The general form of the instructions is as follows:
%[argument_index][flags][width][.precision]type specifier
Now let's decipher everything in order:
  • [argument_index] is an integer indicating the position in the argument list. For example, the link to the first argument is $1, the link to the second argument is $2, etc. If position was not specified, the arguments must be in the same order as they are referenced in the format string.
  • [flags] are special characters for formatting. For example:
    • + flag indicating that if a numeric value is positive, it must include a + sign
    • - means align the result to the left
    • , sets the thousand separator for integers
  • [width] is a positive decimal integer that specifies the minimum number of characters that will be output. If this number is preceded by 0, then the missing characters will be padded with 0, if there is no 0, then with spaces.
  • [.accuracy] is a non-negative integer preceded by a dot. Typically used to limit the number of characters. The specific behavior depends on the specific 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 subsettings, let's imagine that we need a specific output of the number Pi:
String str = String.format("%1$+09.5f", 3.1415926535897);
System.out.print(str);
And accordingly, the output in the console:
+03.14159
Seems easy, right? But when it comes to formatting a number, you can’t ignore DecimalFormat . Let's figure out what this means.

DecimalFormat

DecimalFormat is a class for formatting any number in Java, be it an integer or a floating point number. When a DecimalFormat object is created , you can specify a template for formatting incoming numbers directly in the constructor. This is what our example would look like using DecimalFormat :
DecimalFormat dF = new DecimalFormat( "#.###" );
double value = 72.224463;
System.out.print(dF.format(value));
Console output:
72,224
The #.### line is a pattern that indicates that we are formatting the passed value to 3 decimal places. What other symbols are available for patterns? Here are some of them:
  • # — 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;
  • , — separator grouping sign (for example, thousands separator);
  • ; — separates 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 scientific notation.
Let's take a look at a few examples:
System.out.println(new DecimalFormat( "###,###.##" ).format(74554542.224463));
Console output:
74,554,542.22
System.out.println(new DecimalFormat( "%###.##" ).format(0.723456));
Console output:
%72.35
System.out.println(new DecimalFormat( "000.###" ).format(42.224463));
Console output:
042.224
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("###.###");
dF.applyPattern("000000.000");
dF.applyLocalizedPattern("#,#00.0#");
When we talk about formatting a floating point number, we're quite interested in rounding, aren't we? So, when trimming a number with decimal places beyond the specified pattern, DecimalFormat rounds the number up if the last trimmed number is greater than 5. What if the last trimmed number is 5? Indeed, in this case, this number is exactly in the middle between the nearest integers. Format the output of numbers in Java - 3In this case, the previous number is taken into account. If the previous number is even, rounding is done:
DecimalFormat dF = new DecimalFormat("##.###");
String result = dF.format(56.4595);
System.out.println((result));
Console output:
56,459
If odd, it is not performed:
DecimalFormat dF = new DecimalFormat("##.###");
String str = dF.format(56.4595);
System.out.println((str));
Console output:
56,459
The difference between formatting floating point numbers using String.format() and DecimalFormat.format() is that in the first case there will be trailing zeros, even if there is no fractional part. For example:
String firstStr = String.format("%.4f", 9.00001273);
System.out.println((firstStr));
Console output:
9.0000
DecimalFormat decimalFormat = new DecimalFormat("#.####");
String secondStr = decimalFormat.format(9.00001273);
System.out.println((secondStr));
Console output:
9
As you can see, when formatting the number 9.00001273 with an accuracy of four decimal places, the format() method of the String class will output the value 9.0000 , while the similar format() method of DecimalFormat will output 9 .

BigDecimal and BigInteger

Since we have touched on the topic of rounding numbers in Java, let's talk about how to use the BigDecimal class for such operations . This class is focused on working with really LARGE numbers: for it, the maximum double and float values ​​are too small. 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 format() of the String class you can also format time and date. Format the output of numbers in Java - 4Well, let's take a look at how it's done. First, we would like to remind you that the %t format specifier is used for dates . Second, when formatting a template, additional formatting flags are required for each format specifier for dates. Here are the possible formatting flags for dates:
Flags Description
%tB Full name of the month, for example, January, February, etc.
%tb Abbreviated name of the month, for example, Jan, Feb, etc.
%tA Full name of the day of the week, for example, Sunday, Monday
%ta Abbreviated name of the day of the week, for example, Sun, Mon, etc.
%tY Year in 4 digit format, e.g. 0000 to 9999
%ty Year in 2-digit format, for example, from 00 to 99
%tm The month is formatted with zero at the beginning, for example 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 %tm/%td/%ty format
%td Day of the month in two-digit format, for example 01 to 31
%te Day of the month in format without leading 0, for example from 1 to 31
%tT Time in 24-hour format, for example %tH:%tM:%tS
%tH Hour of day in 24-hour format, from 00 to 23
%tI Hour of day for a 12 hour format, e.g. 01 to 12
%tM The minutes in the hour are formatted with a leading zero, for example 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 a shortened list of possible date formatting flags - there are a lot of them, for every taste. A complete list of them and possible specifiers can be found at this link . Let's look at how to use this. This time we do not use String.format() , but immediately System.out.printf() .

Example 1

In addition, we’ll set the result language 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 specifying a 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:
11 October 2020 13:43:22
Passing the same Date object as an argument so many times... It doesn't look very good, does it? Let's use the $ internal subset 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 our console will not change. There are other equally interesting ways to format dates. You can read about them and a little more about time and date in Java in this material . That's all for today, thanks for your attention!Format the output of numbers in Java - 5
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION