java-输出格式

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 be converted to strings (as you will see later in this lesson), you can use these methods to print out an arbitrary mixture of strings and numbers. The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.

The printf and format Methods

The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println. These methods, format and printf, are equivalent to one another. The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods onSystem.out. Thus, you can use 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 two java.io.PrintStreammethods is the same:

public PrintStream format(String format, Object... args)

where format is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. A simple example would be

System.out.format("The value of " + "the float variable is " +
     "%f, while the value of the " + "integer variable is %d, " +
     "and the string is %s", floatVar, intVar, stringVar);

The first parameter, format, is a format string specifying how the objects in the second parameter, args, are to be formatted. The format string contains plain text as well asformat specifiers, which are special characters that format the arguments of Object... args. (The notation Object... args is called varargs, which means that 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 are many converters, flags, and specifiers, which are documented in java.util.Formatter

Here is a basic example:

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

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

The value of i is: 461012

The printf and format methods are overloaded. Each has 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 is used in place of the decimal place in the English representation of floating point numbers), for example, you would use:

System.out.format(Locale.FRANCE,
    "The value of the float " + "variable is %f, while the " +
    "value of the integer variable " + "is %d, and the string is %s%n",
    floatVar, intVar, stringVar);

An Example

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

Converters and Flags Used in TestFormat.java
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 has leading zeroes as needed, te does not.
ty, tY   A date & time conversion—ty = 2-digit year, 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, with three places after decimal point.

The following program shows some of the formatting that you can do with 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 29, 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 the format and printf methods. Further detail can be found in the Basic I/Osection of the Essential trail, in the "Formatting" page.
Using String.format to create strings is covered in Strings.


The DecimalFormat Class

You can use the java.text.DecimalFormatclass to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. DecimalFormat offers 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, by passing a pattern string to the DecimalFormat constructor. The format() method, whichDecimalFormat inherits from NumberFormat, is then invoked by myFormatter—it accepts a double value as an argument and returns the formatted number in a string:

Here is a sample program that illustrates the use of DecimalFormat:

import java.text.*;

public 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.789
123456.789  ###.##  123456.79
123.78  000000.000  000123.780
12345.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 is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
123456.789 ###.## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.
123.78 000000.000 000123.780 The pattern 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 pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formattedoutput.

« Previous • Trail • Next »



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

Copyright © 1995, 2015 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.

时间: 2024-10-12 00:19:41

java-输出格式的相关文章

初窥java乱码问题

故事起源于这周踩的一个小坑,tomcat本地调启动web时报错.错误提示说有个xml文件的编码有问题,我点进去看了看没看出啥异常,开头跟其他xml一样指定了utf-8的格式,除了是小写的,我傻乎乎地去改成了大写...然后...肯定是没解决啊!!!咳咳,果断请教同事去了,瞅一眼,扔过来一串参数-Dfile.encoding=UTF-8,让我在webserver的VM OPTION里面加上,成了. 恩,又是那个古老的梗,(咦,好了!但是这是为什么呢...)虽然从头到尾我都不懂,但是还是筛选掉一些例如

【Java】编程找出1000以内的所有完数。

1 package com.xt.homework.hw09; 2 /** 3 * 5. 一个正整数,如果恰好等于除它本身外的所有因子之和,这个数就称为"完数". 4 * 例如6=1+2+3,编程找出1000以内的所有完数. 5 * 6 * 7 * @author 天耀二期 8 * 杨勃隆 9 */ 10 public class HomeWork05 { 11 public static void main(String[] args){ 12 { 13 int i,j,k; 14

java统计abacbacdadbc中的每个字母出现的次数,输出格式是:a(4)b(3)c(3)d(2)

原文:http://www.open-open.com/code/view/1456919325625 import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; /* * 统计abacbacdadbc中的每个字母出现的次数,输出格式是:a(4)b(3)c(3)d(2) * * 选中TreeMap的原因是:key不重复且按顺序排序取出 * * 思路: * 1.将字

Java日期时间输出格式优化

使用printf格式化日期 printf 方法可以很轻松地格式化时间和日期.使用两个字母格式,它以 %t 开头并且以下面表格中的一个字母结尾. 转  换  符 说    明 示    例 c 包括全部日期和时间信息 星期六 十月 27 14:21:20 CST 2007 F "年-月-日"格式 2007-10-27 D "月/日/年"格式 10/27/07 r "HH:MM:SS PM"格式(12时制) 02:25:51 下午 T "H

java控制浮点数输出格式

import java.util.*;import java.math.*;import java.text.DecimalFormat;public class Main { public static void main(String args[]) { Scanner cin=new Scanner(System.in); double x1,y1,x2,y2; DecimalFormat df = new DecimalFormat("0.00"); while(cin.has

java服务端json结果集传值给前端的数据输出格式

在服务端输出json数据时按照一定的格式输出时间字段,fastjson支持两种方式:1.使用JSON.toJSONStringWithDateFormat方法2.JSON.toJSONString方法增加SerializerFeature.WriteDateUseDateFormat参数第一种方法的缺点在于:如果在反序列化时没有调用JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm"; 之类设置时间格式,反序列化就会失败! 原文地址:https:

java面试题大全

java面试笔试题大汇总     第一,谈谈final, finally, finalize的区别. 最常被问到. 第二,Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)? 第三,Static Nested Class 和 Inner Class的不同,说得越多越好(面试题有的很笼统). 第四,&和&&的区别. 这个问得很少. 第五,HashMap和Hashtable的区

java学习资料

必须养成好的的编码习惯:缩进(用空格).注释.命名约定. 大小写敏感. 单独的":"代表一条空语句. main函数是我们整个程序的执行入口所以必须是静态公开的. 必须写成这样:  public static void main(String[]args){...} 生成jar包: 在eclipse里,选中要打包的几个文件,右键-Export-写文件名-Next-Next-选main方法的class-finish 在jar包的同一文件夹下,新建一个空文档,写"java -jar

CCF 201612-2 工资计算 java 解题

问题描述 小明的公司每个月给小明发工资,而小明拿到的工资为交完个人所得税之后的工资.假设他一个月的税前工资(扣除五险一金后.未扣税前的工资)为S元,则他应交的个人所得税按如下公式计算: 1) 个人所得税起征点为3500元,若S不超过3500,则不交税,3500元以上的部分才计算个人所得税,令A=S-3500元: 2) A中不超过1500元的部分,税率3%: 3) A中超过1500元未超过4500元的部分,税率10%: 4) A中超过4500元未超过9000元的部分,税率20%: 5) A中超过9

Java面试12|Linux及Shell脚本

1.关于awk命令的面试题 (1)最近登录的5个帐号 last -n 5 | awk -F ':'(指定域分割符号) '{print $1}' -n表示number,有多少行需要显示.读入有'\n'换行符分割的一条记录,然后将记录按指定的域分隔符划分域,填充域,$0则表示所有域,$1表示第一个域,$n表示第n个域.默认域分隔符是"空白键" 或 "[tab]键",所以$1表示登录用户,$3表示登录用户ip,以此类推. (2)用awk统计文本行数 awk '{count