How to format output numbers in Java

Source: Internet
Author: User
Tags locale

In the actual work, often need to set the output format of the number, such as in the form of a percentage of output, or set the number of decimal place, and now a little summarized as followsmain classes used: Java.text.DecimalFormat1. There are two ways to instantiate an object:

The code is as follows:
DecimalFormat df= (DecimalFormat) numberformat.getinstance ();
DecimalFormat df1= (DecimalFormat) decimalformat.getinstance ();

Because DecimalFormat inherits from NumberFormat.

2. Set the number of decimal digits

The default scale of the system is 3, such as:

The code is as follows:
DecimalFormat df= (DecimalFormat) numberformat.getinstance ();
System.out.println (Df.format (12.3456789));

Output: 12.346

It is now possible to set the decimal to two bits by the following method:

The code is as follows:
Df.setmaximumfractiondigits (2);
System.out.println (Df.format (12.3456789));

The output is: 12.35

3. Convert a number to a percent output, as in the following two ways:

(1)

The code is as follows:
Df.applypattern ("##.##%");
System.out.println (Df.format (12.3456789));
System.out.println (Df.format (1));
System.out.println (Df.format (0.015));

Outputs are: 1234.57% 100% 1.5%, respectively

(2)

The code is as follows:
Df.setmaximumfractiondigits (2);
System.out.println (Df.format (12.3456789*100) + "%");
System.out.println (Df.format (1*100) + "%");
System.out.println (Df.format (0.015*100) + "%");

The outputs are:

1,234.57% 100% 1.5%

4. Set the grouping size

The code is as follows:
DecimalFormat df1= (DecimalFormat) decimalformat.getinstance ();
Df1.setgroupingsize (2);
System.out.println (Df1.format (123456789));

Output: 1,23,45,67,89

You can also disable grouping settings by df1.setgroupingused (false), such as:

Copy CodeThe code is as follows:
DecimalFormat df1= (DecimalFormat) decimalformat.getinstance ();
Df1.setgroupingsize (2);
Df1.setgroupingused (FALSE);
System.out.println (Df1.format (123456789));

Output: 123456789

5. Set the decimal number to be 2 bits

The code is as follows:
DecimalFormat df2= (DecimalFormat) decimalformat.getinstance ();
Df2.applypattern ("0.00");
System.out.println (Df2.format (1.2));

Output: 1.20

Sometimes we need to control the output of the number format, how to use the Java class Library to do this?
Maybe you don't care about the format, but you need to be concerned that your program can be used around the world, such a simple statement like this one is dependent on the region:
System.out.println (1234.56);
In the United States, "." is a decimal point, but it is not necessarily in other places. How do we handle this?
Some of the packages in the Java.text package can handle this kind of problem. The following simple example uses those classes to solve the problem raised above:

The code is as follows:
Import Java.text.NumberFormat;
Import Java.util.Locale;
public class DecimalFormat1 {
public static void Main (String args[]) {
Get the local default format
NumberFormat Nf1 = Numberformat.getinstance ();
System.out.println (Nf1.format (1234.56));
Get the German format
NumberFormat Nf2 =
Numberformat.getinstance (Locale.german);
System.out.println (Nf2.format (1234.56));
}     }

If you are in the United States, run the program after the output:
1,234.56
1.234,56
In other words, use different habits to represent numbers in different places.
The Numberformat.getinstance () method returns an instance of NumberFormat (actually numberformat a specific subclass, such as DecimalFormat), which is suitable for formatting a number based on local settings. You can also use non-default locale settings, such as Germany. The formatting method then formats the numbers according to the specific locale rules. This program can also be used in a simple form:
Numberformat.getinstance (). Format (1234.56)
But saving a format and reusing it is more efficient. Internationalization is a big problem when formatting numbers.
The other is the effective control of the format, such as specifying the number of bits in the fractional part, and here is a simple example of solving this problem:

The code is as follows:
Import Java.text.DecimalFormat;
Import Java.util.Locale;
public class DecimalFormat2 {
public static void Main (String args[]) {
Get the local default format
DecimalFormat df1 = new DecimalFormat ("####.000");
System.out.println (Df1.format (1234.56));
Get the German format
Locale.setdefault (Locale.german);
DecimalFormat DF2 = new DecimalFormat ("####.000");
System.out.println (Df2.format (1234.56));
}
}

In this example, the format of the numbers is set, using symbols like "####.000". This pattern means that there are four digits before the decimal point, and if not enough, there are three digits after the decimal point, which is less than 0. Output of the program:
1234.560
1234,560
Similarly, you can control the format of the exponential form, for example:

The code is as follows:
Import Java.text.DecimalFormat;
public class DecimalFormat3 {
public static void Main (String args[]) {
DecimalFormat df = new DecimalFormat ("0.000E0000");
System.out.println (Df.format (1234.56));
}
}

Output:
1.235E0003
For percentages:

The code is as follows:
Import Java.text.NumberFormat;
public class DecimalFormat4 {
public static void Main (String args[]) {
NumberFormat NF = numberformat.getpercentinstance ();
System.out.println (Nf.format (0.47));
}
}

Output:
47%
So far, you've seen several different techniques for formatting numbers. On the other hand, how can I read and parse a string containing formatted numbers? Parsing support is included in the NumberFormat. For example:

The code is as follows:
Import Java.util.Locale;
Import Java.text.NumberFormat;
Import java.text.ParseException;
public class DecimalFormat5 {
public static void Main (String args[]) {
Local format
NumberFormat Nf1 = Numberformat.getinstance ();
Object obj1 = null;
Format-based parsing
try {
Obj1 = Nf1.parse ("1234,56");
}
catch (ParseException E1) {
SYSTEM.ERR.PRINTLN (E1);
}
System.out.println (OBJ1);
German format
NumberFormat Nf2 =
Numberformat.getinstance (Locale.german);
Object obj2 = null;
Format-based parsing
try {
Obj2 = Nf2.parse ("1234,56");
}
catch (parseexception E2) {
SYSTEM.ERR.PRINTLN (E2);
}
System.out.println (OBJ2);
}
}

This example is divided into two parts, parsing a string: "1234,56". The first section uses local format parsing, and the second part uses German format parsing. When the program runs in the United States, the result is:
123456
1234.56
In other words, "1234,56" in the United States is considered to be a huge integer 123456, while in Germany is considered a decimal "1234.56".
There is also the last question of formatting discussions. In the example above, both DecimalFormat and NumberFormat are used. DecimalFormat are often used for good format control, and NumberFormat are often used to designate regions that are different from the local. How to combine two classes?
The answer revolves around the fact that DecimalFormat is a subclass of NumberFormat whose instances are designated as specific regions. Therefore, you can use Numberformat.getinstance to specify a region and then cast the structure to a DecimalFormat object. The documentation mentions that this technique can be applied in most cases, but you need to surround the cast with a try/catch block to prevent the conversion from working (probably using a singular area in very unclear circumstances). Here is an example of this:

The code is as follows:
Import Java.text.DecimalFormat;
Import Java.text.NumberFormat;
Import Java.util.Locale;
public class DecimalFormat6 {
public static void Main (String args[]) {
DecimalFormat df = null;
Get a NumberFormat object and
Cast to a DecimalFormat object
try {
DF = (DecimalFormat)
Numberformat.getinstance (Locale.german);
}
catch (ClassCastException e) {
System.err.println (e);
}
Setting the format pattern
Df.applypattern ("####.00000");
Format a number
System.out.println (Df.format (1234.56));
}
}

The getinstance () method obtains the format, and then calls the Applypattern () method to set the format pattern, output:
1234,56000
If you don't care about internationalization, you can use DecimalFormat directly.

How to format output numbers in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.