java-output format

Source: Internet
Author: User

Https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Formatting Numeric Print Output

Earlier you saw the use of the print and println methods for printing strings to standard output ( System.out ). Since all numbers can is converted to strings (as you'll see later in this lesson), you can use these methods to print O UT an arbitrary mixture of strings and numbers. The Java programming language have other methods, however, which allow you to exercise much more control over your print out Put when numbers is included.

The printf and format Methods

The package java.io includes a class this has both formatting methods that's can use to PrintStream Replace and print println . These methods, format and printf , is equivalent to one another. The familiar System.out that has been using happens PrintStream to is a object, so you can invoke PrintStream methods on System.out . Thus, you can use the format or printf anywhere in your code where you have previously been using print or println . For example,

System.out.format (...);

The syntax for these and java.io.PrintStream methods is the same:

Public printstream Format (String format, Object ... args)

Where is a string this specifies the formatting to being used and is a list of the variables to be format args printed using that formatting. A Simple example would is

System.out.format ("The value of" + "the float variable is" +     "%f, while the value of the" + "Integer variable is%d , " +     

The first parameter, format a format string specifying how the objects in the second parameter, args Ted. The format string contains plain text as well asformat specifiers, which is special characters that format the A Rguments of Object... args . (The notation Object... args is called varargs, which means, and the number of arguments may vary.)

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating, the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There is many converters, flags, and specifiers, which is documented injava.util.Formatter

Here is a basic example:

int i = 461012; System.out.format ("The value of I is:%d%n", i);

The %d specifies the single variable is a decimal integer. The is %n a platform-independent newline character. The output is:

The value of I is:461012

The printf and format methods are overloaded. Each have a version with the following syntax:

Public printstream format (Locale L, String format, Object ... args)

To print numbers in the French system (where a comma are used in place of the decimal place in the Chinese representation o F floating point numbers), for example, your would use:

System.out.format (Locale.france,    "The value of the float" + "variable is%f and while the" +    "value of the integer Variable "+" is%d, and the string is%s%n ",     
An Example

The following table lists some of the converters and flags that is used in the sample program, TestFormat.java which that follows the TA ble.

Converters and Flags used TestFormat.java in
Converter Flag explanation
D A decimal Integer.
F A float.
N A New line character appropriate to the platform running the application. You should always use %n , rather than \n .
TB A Date & Time conversion-locale-specific full name of month.
TD, TE A Date & Time Conversion-2-digit day of month. TD have leading zeroes as needed, TE does not.
Ty, Ty. A Date & Time Conversion-ty = 2-digit year, and Ty = 4-digit year.
Tl A Date & Time Conversion-hour in 12-hour clock.
Tm A Date & Time conversion-minutes in 2 digits with leading zeroes as necessary.
Tp A Date & Time conversion-locale-specific am/pm (lower case).
Tm A Date & Time conversion-months in 2 digits with leading zeroes as necessary.
Td A Date & Time conversion-date as%tm%td%ty
08 Eight characters in width, with leading zeroes as necessary.
+ Includes sign, whether positive or negative.
, Includes locale-specific grouping characters.
- Left-justified.
.3 Three places after decimal point.
10.3 Ten characters in width, right justified, and three places after decimal point.

The following program shows some of the formatting format . The output is shown within double quotes in the embedded comment:

Import Java.util.calendar;import Java.util.locale;public class Testformat {public static void main (string[] args)      {Long n = 461012;      System.out.format ("%d%n", N);    --"461012" System.out.format ("%08d%n", N);    --"00461012" System.out.format ("%+8d%n", N);    --"+461012" System.out.format ("%,8d%n", N); --"461,012" System.out.format ("%+,8d%n%n", N);      --"+461,012" double pi = Math.PI;       System.out.format ("%f%n", pi);     --"3.141593" System.out.format ("%.3f%n", pi);   --"3.142" System.out.format ("%10.3f%n", pi);  --"3.142" System.out.format ("%-10.3f%n", pi); --"3.142" System.out.format (locale.france, "%-10.4f%n%n", pi);      --"3,1416" Calendar C = calendar.getinstance (); System.out.format ("%tb%te,%ty%n", C, C, c); -"May, 2006" System.out.format ("%tl:%tm%tp%n", C, C, c);    --"2:34 AM" System.out.format ("%td%n", c); --"05/29/06"}}
Note:The discussion in this section covers just the basics of theformatandprintfMethods. Further detail can be found in theBasic I/Osection of the Essential Trail, in the "Formatting" page.
UsingString.formatTo create strings are covered in strings. The DecimalFormat Class

You can use java.text.DecimalFormat the class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (Thousan DS) separators, and the decimal separator. DecimalFormatoffers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.

The example that follows creates a DecimalFormat object, myFormatter and by passing a pattern string to the DecimalFormat constructor. format()the method, which DecimalFormat inherits from NumberFormat , was then invoked by myFormatter -it accepts a double value as an argument and RET Urns the formatted number in a string:

Here's a sample program, that illustrates, the use of DecimalFormat :

Import java.text.*;p Ublic class Decimalformatdemo {   static public void CustomFormat (String pattern, double value) {
   decimalformat myformatter = new DecimalFormat (pattern);      String output = Myformatter.format (value);      System.out.println (value + "  + pattern +"  + output);   }   static public void Main (string[] args) {      CustomFormat ("###,###.###", 123456.789);      CustomFormat ("###.##", 123456.789);      CustomFormat ("000000.000", 123.78);      CustomFormat ("$###,###.###", 12345.67);     }}

The output is:

123456.789  ###,###.###  123,456.789123456.789  ###.##  123456.79123.78  000000.000  000123.78012345.67  $###,###.###  $12,345.67

The following table explains each line of output.

DecimalFormat.java Output
Value Pattern Output explanation
123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit, the comma are a placeholder for the grouping separator, and the period are a placeholder for the decimal separator.
123456.789 ###.## 123456.79 valuethe have three digits to the right of the decimal point, but the have only pattern . The format method handles the rounding up.
123.78 000000.000 000123.780 patternthe specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
12345.67 $###,###.### $12,345.67 The first character in the are the pattern dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output .
«previous Trail Next»

Your use of this page and all the material on pages under "The Java Tutorials" banner are subject to these legal notices.

copyright©1995, Oracle and/or its affiliates. All rights reserved.

Problems with the examples? Try compiling and Running the Examples:faqs.

Complaints? Compliments? Suggestions? Give us your feedback.

java-output format

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.