System.out.format的使用

版权声明:本文为【博主: 乐意黎 http://blog.csdn.net/aerchi】原创文章,未经允许不得博客镜像、采集,转载需注明来源。

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"

}

}

====================

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

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.

JDK5.0允许象C语言那样直接用printf()方法来格式化输出,并且提供了许多参数来格式化输入,调用也很简单:


System.out.format("Pi is approximately  %f", Math.Pi);

System.out.printf("Pi is approximately  %f", Math.Pi);

printf()和 format() 方法具有相同的功能. System.out 是 Java.io.PrintStream的实例PrintStreamjava.io.PrintWriter,
和 java.lang.String 每个类都有四个新的格式化方法:

format( String format, Object... args);

printf( String format, Object... args);

format( Locale locale, String format, Object... args);

printf( Locale locale, String format, Object... args);

同时,以前的formatter类也提供了更完善的方法来格式化,例如:


formatter.format("Pi is approximately %1$f," +

"and e is about %2$f", Math.PI, Math.E);

格式化元素的构成如下:


%[argument_index$][flags][width][.precision]conversion

其中:

argument_index是一个正整数,说明了参数的位置,1为取第一个参数

width表示输出的最小字母个数

precision代表数字的小数位数

conversion代表被格式化的参数的类型:

f  float,

t  time

d  decimal

o octal

x  hexadecimal

s  general

c  a Unicode character

以下是个例子:


package format;

import java.util.Formatter;

public class UsingFormatter {

public static void main(String[] args) {

if (args.length != 1) {

System.err.println("usage: " +

"Javaformat/UsingFormatter ");

System.exit(0);

}

String format = args[0];

StringBuilder stringBuilder = new StringBuilder();

Formatter formatter = new Formatter(stringBuilder);

formatter.format("Pi is approximately " + format +

", and e is about " + format, Math.PI, Math.E);

System.out.println(stringBuilder);

}

}

//控制台调用

javaformat/UsingFormatter %f

//输出

Pi is approximately 3.141593, and e is about 2.718282

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3.14, and e is about 2.72

//控制台调用

java format/UsingFormatter %6.2f

//输出(有空格来填补长度)

Pi is approximately   3.14, and e is about   2.72

//控制台调用

java format/UsingFormatter  %1$.2f

//输出

Pi is approximately 3.14, and e is about 3.14

//改变区域设置

package format;

import java.util.Formatter;

import java.util.Locale;

public class UsingFormatter {

public static void main(String[] args) {

if (args.length != 1) {

System.err.println("usage: " +

"java format/UsingFormatter <format string>");

System.exit(0);

}

String format = args[0];

StringBuilder stringBuilder = new StringBuilder();

Formatter formatter = new Formatter(stringBuilder,

Locale.FRANCE);

formatter.format("Pi is approximately " + format +

", and e is about " + format, Math.PI, Math.E);

System.out.println(stringBuilder);

}

}

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3,14, and e is about 2,72

//采用format,printf的可替代写法

package format;

public class UsingSystemOut {

public static void main(String[] args) {

if (args.length != 1) {

System.err.println("usage: " +

"java format/UsingSystemOut <format string>");

System.exit(0);

}

String format = args[0];

System.out.format("Pi is approximately " + format +

", and e is approximately " + format, Math.PI, Math.E);

}

}

//控制台调用

java format/UsingSystemOut %.2f%n

//输出

Pi is approximately 3.14

, and e is about 2.72

对时间的格式化用字母t来代表,通常在t后面加上特殊的字符来显示时间的某个部分:

tr  hour and minute,

tA  the day of the week

tB  the name of the month

te  the number of the day of the month

tY  the year

//eg.

package format;

import java.util.Calendar;

public class FormattingDates  {

public static void main(String[] args) {

System.out.printf("Right now it is %tr on " +

"%<tA, %<tB %<te, %<tY.%n",

Calendar.getInstance());

}

}

//说明:“<”指示采用的参数为前一个被格式化的参数

//输出

Right now it is 01:55:19 PM on Wednesday, September 22, 2004.

时间: 2024-11-07 00:16:21

System.out.format的使用的相关文章

A printf format reference page (cheat sheet)

Summary: This page is a printf formatting cheat sheet. I originally created this cheat sheet for my own purposes, and then thought I would share it here. A cool thing about the printf formatting syntax is that the specifiers you can use are very simi

基于system Center 2012&ndash;VMM(virtral machine manager)在线扩容Centos硬盘。

计划使用zabbix监控管理全单位的PC的基本硬件信息,由于开始的规划的硬盘比较小,担心监控时磁盘不够. 在些先考虑能过LVM增容zabbix的数据库存储空间. System Center 2012–VMM(virtral machine manager)-简称为:VMM 1.打开VMM管理台,找到增容的设备-右键属性-硬件配置-磁盘(增加)自定义需要增加的容量后,点击:确认 2.SSH连接Centos虚拟机器,查看新增硬盘设备 [[email protected] ~]# dmesg | gr

C# 字符串拼接性能探索 c#中+、string.Concat、string.Format、StringBuilder.Append四种方式进行字符串拼接时的性能

本文通过ANTS Memory Profiler工具探索c#中+.string.Concat.string.Format.StringBuilder.Append四种方式进行字符串拼接时的性能. 本文涉及程序为.NET Core 2.0控制台应用程序. 一.常量字符串拼接 private static void TestPerformance(Action action, int times) { Stopwatch sw = new Stopwatch(); sw.Start(); for(i

System.arraycopy 和 Array.clone 的比较

1 /** 2 * 复制功能更测试 3 */ 4 public static void main01(String[] args) { 5 String[] array01 = new String[]{"01", "02", "03"}; 6 String[] array02 = array01.clone(); 7 System.out.println(array01); 8 System.out.println(array02); 9 ar

.Net:System.Guid

ylbtech-.Net:System.Guid 1.返回顶部 1.public static Guid NewGuid(); // // 摘要: // 初始化 System.Guid 结构的新实例. // // 返回结果: // 一个新的 GUID 对象. [SecuritySafeCritical] public static Guid NewGuid(); // // 摘要: // GUID 的字符串表示转换为等效的 System.Guid 结构. // // 参数: // input:

System.nanoTime()和System.currentTimeMillis()性能问题

之前给模块做性能优化的时候,需要将性能调到毫秒级,使用了System.nanoTime()和System.currentTimeMillis()对代码分片计时分析耗时操作,后发现在串行情况下性能达到毫秒级,但是一旦在并发压测的时候,性能急剧下降,后经多方排查,发现原因出在System.nanoTime()和System.currentTimeMillis()这两个api上,其在并发情况下耗时会急剧上升,当然在整体上看依然很快,但是在高性能场景下就有很显著的影响.特此记录一下. 测试代码: 1 p

PAT甲级考试题库1001 A+B Format 代码实现及相关知识学习

准备参加九年九月份的PAT甲级证书考试,对网站上的题目进行总结分析: 1001题 A+B Format (20 分) Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). 计算a+b的值并以一定格式输出其和sum(数字需要

System.Globalization.DateTimeFormatInfo.cs

ylbtech-System.Globalization.DateTimeFormatInfo.cs 1.返回顶部 1. #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\mscorlib.dll

《Java编程思想》第十三章 字符串

<Java编程思想>读书笔记 1.String作为方法的参数时,会复制一份引用,而该引用所指的对象其实一直待在单一的物理位置,从未动过. 2.显式地创建StringBuilder允许预先为他指定大小.如果知道字符串多长,可以预先指定StringBuilder的大小避免多次重新分配的冲突. 1 /** 2 * @author zlz099: 3 * @version 创建时间:2017年9月1日 下午4:03:59 4 */ 5 public class UsingStringBuilder {