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.PrintStream
methods 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.
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/O
section 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.DecimalFormat
class 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.
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 . |
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. |
java-输出格式的更多相关文章
- java输出格式-----System.out.printf()
package com.lzc.test; public class Main { public static void main(String[] args) { // 定义一些变量,用来格式化输出 ...
- java 初学者 第一阶段作业编程总结及心得体会
0.前言 第一阶段java作业分为3次. 第一次作业是简单得一些语法和一些简单得逻辑思维,主要内容有求三角形是什么三角形的,还有就是求坐标点所在范围的,也涉及到了数字和字母的转换,总之相相当于是给ja ...
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
- Java中通过SimpleDateFormat格式化当前时间:/** 输出格式:20060101010101001**/
import java.util.*; import java.text.SimpleDateFormat; int y,m,d,h,mi,s,ms; String cur; Calendar cal ...
- java统计abacbacdadbc中的每个字母出现的次数,输出格式是:a(4)b(3)c(3)d(2)
import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; /* ...
- java的acm输入输出格式+大数语法
1.类名称必须采用public class Main方式命名 2.多组输入,读取到文件尾 Scanner scan=new Scanner(System.in); while(scan.hasNext ...
- Java日期时间输出格式优化
使用printf格式化日期 printf 方法可以很轻松地格式化时间和日期.使用两个字母格式,它以 %t 开头并且以下面表格中的一个字母结尾. 转 换 符 说 明 示 例 c 包括全部 ...
- java服务端json结果集传值给前端的数据输出格式
在服务端输出json数据时按照一定的格式输出时间字段,fastjson支持两种方式:1.使用JSON.toJSONStringWithDateFormat方法2.JSON.toJSONString方法 ...
- 关于java日期输出格式
String.format("%tY%tm", new Date(), new Date()): //201905 String.format("%tY-%tm" ...
- Java 字符串格式化详解
Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...
随机推荐
- rsyslog 不打印日志到/var/log/messages
*.info;mail.none;authpriv.none;cron.none;local3.none /var/log/messages 表示 所有来源的info级别都记录到/var/log/me ...
- Mirantis Certification summary
preface Mirantis Certification (MCA100 )summary roughly question types handy remain by Ruiy!
- Swift中类的初始化器与继承
初始化是类,结构体和枚举类型实例化的准备阶段.这个阶段设置这个实例存储的属性的初始化数值和做一些使用实例之前的准备以及必须要做的其他一些设置工作. 通过定义构造器(initializers)实现这个实 ...
- Glog
Glog的简单入门,glog虽然在配置参数方面比较麻烦,但是在小规模程序中,由于其简单灵活,也许会有优势. 0, glog 是google的开源日志系统,相比较log4系列的日志系统,它更加轻巧灵活 ...
- 【转】sqlserver数据库之间的表的复制
以下以数据库t1和test为例. 1.复制表结构及资料 select * into 数据库名.dbo.表名 from 源表(全部数据) 如:select * into t1.dbo.YS1 ...
- Git跨平台中文乱码临时解决方案
Git 是一个非常优秀的分布式版本控制系统,最初为Linux Kernel版本管理进行量身定做.优点是,和其他版本控制系统相比,稳定,速度快,跨平台,易学易用,无需要花费成本.更多优点请点击阅读:ht ...
- C# 课堂总结3-语句
一.顺序语句 二.条件,分支语句 1.if语句 关键是能够熟练运用 if的嵌套.要考虑好所有的情况. 如果说 条件是两种+情况相互对应的,那么就可以只用 if 与else .但必须要想好 每个else ...
- JavaSE_ 面向对象 总目录(7~10)
JavaSE学习总结第07天_面向对象2 07.01 成员变量和局部变量的区别07.02 方法的形式参数是类名的调用07.03 匿名对象的概述和应用07.04 封装的概述07.05 封装的好处和设计原 ...
- RAC ORA-12170 ora-12535/tns-12535
现象:开发人员抱怨RAC数据库出现了时连得上时连不上的情况,用SQLPLUS一试,果然有这样的情况: SQL> conn system/*******@bjyd 已连接. SQL> con ...
- 如何管理安卓android手机下google(谷歌)的通讯录联系人账户
andorid手机都自带通讯录备份功能,但是如何管理,一直是一些人头疼的问题.经常在手机备份还原之后发现很多联系人都有重复. 1.打开 :https://mail.google.com/ 用你的谷歌账 ...