在C中可以使用类似printf(“%d %8.2f\n”, 1001, 52.335)的方法实现格式化输出,可是Java中的System.out.println()并没有对应的功能。要格式化输出,必须使用java.text包中的类来实现类似的操作(要不怎么体现面向对象的优越性呢,不过据说jdk1.5准备又补上)。当然了,java.text包的功能还是很强大的,奇怪的是很多书中都没有涉及,而一般谁又有工夫整天去看API?

注意:由于这里说得很简略,因此请参照下面的Demo程序。

格式化数字

在NumberFormat类中为我们提供了格式化4种数字的方法:整数、小数、货币和百分比,通过工厂方法getNumberInstance, getNumberIntance, getCurrencyInstance, getPercentInstance方法获得相应的实例对象就行。例如我们要以字符串表示人民币88888.88元,这样来写就行:

NumberFormat nf = NumberFormat.getCurrencyInstance();

System.out.println(nf.format(88888.88));

定制格式化数字

可是对于稍微复杂一点的需求,NumberFormat就满足不了了,幸好java还提供了DecimalFormat实现定制的格式化。要使用DecimalFormat对象,必须提供给它提供一个格式化的模式(pattern):

String pattern = …

DecimalFormat df = new DecimalFormat(pattern);

或者:

DecimalFormat df = new DecimalFormat();

df. applyPattern(pattern);

然后就调用它的format方法就行了。

所以关键就是这个模式怎么定义。在DecimalFormat类的JavaDoc中有模式的语法表示,不过很难说清楚(是我说不清楚,呵呵),请看看Demo自己多试试吧。下面是模式中某些字符的含义表:

字符

含义

0

一位数字,这一位缺失显示为0。用来补零

#

一位数字, 这一位缺失就不显示

.

小数点,不用多说了吧

,

千位分隔符

E

科学计数法

%

百分比

格式化日期

把日期转化为字符串最简单的方法就是调用Date类的toString或者toLocaleString方法:

System.out.println(new Date());

输出:2004-8-7 8:16:14。可是如果我们想把月和日补成2位不要时分秒2004-08-07,这就不灵了。java.text.DateFormat提供了大量的工厂方法:getDateInstance(int style), getTimeInstance(int style), getDateTimeInstance(int dateStyle, int timeStyle)等等。其中style必须是DateFormat.LONG, DateFormat.MEDIUM, DateFormat.SHORT之一。Demo中的defaultDateFormat方法作了一个简单的实验。

定制格式化日期:

同样,java.text.SimpleDateFormat可以通过模式(pattern)实现定制格式化:

String pattern = …

SimpleDateFormat df = new SimpleDateFormat(pattern);

或者:

SimpleDateFormat df = new SimpleDateFormat();

df. applyPattern(pattern);

下面是SimpleDateFormat的javadoc中的一个模式符号简表:

符号

意义

合法数值

示例

y

Year

Year

1996; 96

M

Month in year

Month

July; Jul; 07

d

Day in month

Number

10

a

Am/pm marker

Text

PM

H

Hour in day (0-23)

Number

0

h

Hour in am/pm (1-12)

Number

12

m

Minute in hour

Number

30

s

Second in minute

Number

55

S

Millisecond

Number

978

z

Time zone

General time zone

Pacific Standard Time; PST; GMT-08:00

Z

Time zone

RFC 822 time zone

-0800

注意的是,符号的大小写意义是不同的,符号的个数也会导致输出不一样。例如用MM就会把1月份显示成01,而用M则不会补零。对于年份,两个yy会只输出两位年份,yyyy则会输出4位年份。

实际上,上面的类还提供了很多其他方法,特别是用于本地化(Locale)定制格式化的方法,以及从字符串表示转化为相应对象的parse方法,还有把格式化结果附加到一个StringBuffer的方法(应该是用来提高性能)。

最后是一个小Demo和输出结果:

TestFormat.java:

import java.text.*;

import java.util.*;

public class TestFormat {

public static void main(String[] args) {

defaultNumberFormat();

System.out.println();

customNumberFormat();

System.out.println();

defaultDateFormat();

System.out.println();

customDateFormat();

System.out.println();

}

public static void defaultNumberFormat() {

int i = 123456;

double x = 882323.23523;

double p = 0.528;

double c = 52.83;

NumberFormat nf = NumberFormat.getInstance();

System.out.println("Integer " + i + " is displayed as " + nf.format(i));

System.out.println("Double " + x + " is displayed as " + nf.format(x));

NumberFormat nfInt = NumberFormat.getIntegerInstance();

System.out.println("Integer " + i + " is displayed as " + nfInt.format(i));

NumberFormat nfNumber = NumberFormat.getNumberInstance();

System.out.println("Double " + x + " is displayed as " + nfNumber.format(x));

NumberFormat nfPercent = NumberFormat.getPercentInstance();

System.out.println("Percent " + p + " is displayed as " + nfPercent.format(p));

NumberFormat nfCurrency = NumberFormat.getCurrencyInstance();

System.out.println("Currency " + p + " is displayed as " + nfCurrency.format(c));

//这里没有涉及相应的parse方法

}

public static void customNumberFormat() {

double x = 1000.0 / 3;

System.out.println("default output is " + x);

patternPrint("###,###.##", x);

patternPrint("####.##", x);

patternPrint("####.00", x);

patternPrint("####.0#", x);

patternPrint("00000.##", x);

patternPrint("$###,###.##", x);

patternPrint("0.###E0", x);

patternPrint("00.##%", x);

double y = 23.0012;

System.out.println("default output is " + y);

patternPrint("###,###.##", y);

patternPrint("####.##", y);

patternPrint("####.00", y);

patternPrint("####.0#", y);

patternPrint("00000.##", y);

patternPrint("$###,###.##", y);

patternPrint("0.###E0", y);

patternPrint("00.##%", y);

}

public static void patternPrint(String pattern, double x) {

DecimalFormat df = new DecimalFormat(pattern);

System.out.println("output for pattern " + pattern + " is " + df.format(x));

}

public static void defaultDateFormat(){

Date date = new Date();

System.out.println("simple date " + date.toLocaleString());

DateFormat df = DateFormat.getDateTimeInstance();

System.out.println(df.format(date));

DateFormat dfLong = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);

System.out.println(dfLong.format(date));

DateFormat dfMedium = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,

DateFormat.MEDIUM);

System.out.println(dfMedium.format(date));

DateFormat dfShort = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);

System.out.println(dfShort.format(date));

}

public static void customDateFormat() {

Date date = new Date();

patternPrint("yyyy.MM.dd HH:mm:ss z", date);  //两个MM, dd会导致补零

patternPrint("yy年M月d日 HH时mm分", date);  //两个yy就显示为两位年份

patternPrint("EEE, MMM d, ''yy", date);

patternPrint("h:mm a", date);

patternPrint("hh 'o''clock' a, zzzz", date);

patternPrint("yyyyy.MMMMM.dd GGG hh:mm aaa", date);

patternPrint("EEE, d MMM yyyy HH:mm:ss Z", date);

patternPrint("yyMMddHHmmssZ", date);

}

public static void patternPrint(String pattern, Date date){

SimpleDateFormat df = new SimpleDateFormat(pattern);

System.out.println(df.format(date));

}

}

输出:

Integer 123456 is displayed as 123,456

Double 882323.23523 is displayed as 882,323.235

Integer 123456 is displayed as 123,456

Double 882323.23523 is displayed as 882,323.235

Percent 0.528 is displayed as 53%

Currency 0.528 is displayed as ¥52.83

default output is 333.3333333333333

output for pattern ###,###.## is 333.33

output for pattern ####.## is 333.33

output for pattern ####.00 is 333.33

output for pattern ####.0# is 333.33

output for pattern 00000.## is 00333.33

output for pattern $###,###.## is $333.33

output for pattern 0.###E0 is 3.333E2

output for pattern 00.##% is 33333.33%

default output is 23.0012

output for pattern ###,###.## is 23

output for pattern ####.## is 23

output for pattern ####.00 is 23.00

output for pattern ####.0# is 23.0

output for pattern 00000.## is 00023

output for pattern $###,###.## is $23

output for pattern 0.###E0 is 2.3E1

output for pattern 00.##% is 2300.12%

simple date 2004-8-7 8:16:14

2004-8-7 8:16:14

2004年8月7日 上午08时16分14秒

2004-8-7 8:16:14

04-8-7 上午8:16

2004.08.07 08:16:14 GMT+08:00

04年8月7日 08时16分

星期六, 八月 7, '04

8:16 上午

08 o'clock 上午, GMT+08:00

02004.八月.07 公元 08:16 上午

星期六, 7 八月 2004 08:16:14 +0800

040807081614+0800

转载于:https://www.cnblogs.com/ahuo/archive/2007/01/03/610316.html

使用java.text包格式化数字和日期相关推荐

  1. Java学习之路-数字和日期处理

    数字和日期处理 一.概念 1.数字处理类 ​ 在解决实际问题时,对数字的处理是非常普遍的,如数学问题.随机问题等,为了应对以上问题,java提供了处理相关问题的类,包括: DecimalFormat类 ...

  2. Java入门教程五(数字和日期处理)

    Java 提供了处理相关问题的类,包括 Math 类.Random 类.BigInteger 类.Date 类等. Math类 Math 类封装了常用的数学运算,提供了基本的数学操作,如指数.对数.平 ...

  3. 使用MessageFormat格式化数字,日期

    http://www.cppblog.com/biao/archive/2010/12/01/135119.html 如数字上加逗号,保留小数点后面两位(会自动四舍五入),百分比,货币等. 参考实例: ...

  4. java什么是格式化数字,java中对数字进行格式化

    在java中我们都是用java.text.DecimalFormat类来专门处理对数字的格式化操作.它是用字符串类型pattern提供格式化模式,利用applyPattern方法设置模式.最后调用fo ...

  5. java.text.dateformat_使用java.text.SimpleDateFormat类进行文本日期和Date日期的转换

    Date类内部既不存储年月日也不存储时分秒,而是存储一个从1970年1月1日0点0分0秒开始的毫秒数,而真正有用的年月日时分秒毫秒都是从这个毫秒数转化而来,这是它不容易被使用的地方,尤其是显示和存储的 ...

  6. Oracle格式化数字和日期的方法

    http://blog.csdn.net/szwangdf/article/details/1570005 to_char,函数功能,就是将数值型或者日期型转化为字符型. 比如最简单的应用: /*1. ...

  7. Java Date类型格式化,不同日期格式转换,获取N天后的日期,CommonUtil工具

    文章目录 Date类型格式化为各种格式字符串 不同日期格式的字符串之间的转换 获取N天后的日期 实用工具类库common-util使用 参考链接 Date类型格式化为各种格式字符串 java 日期格式 ...

  8. d在java那个包中_处理日期的类在Java的哪个包中()A、java.utilB、java.ioC、java.langD...

    一般曳引机三点连接举升装置的液压缸是采用(). 在税控服务器管理系统中,以下描述错误的是() "去繁求简.去粗存精",是指什么变化表现方法() 当一个实际电压源(戴维宁电路)对外开 ...

  9. JAVA中计算百分比 格式化数字

    JAVA中计算百分比 格式化数字 这个是我在程序使用的例子: public String myPercent(int y,int z){    String baifenbi="" ...

  10. Date类(java.util)和SimpleDateFormat类(java.text)

    在程序开发中,经常需要处理日期和时间的相关数据,此时我们可以使用 java.util 包中的 Date 类.这个类最主要的作用就是获取当前时间,我们来看下 Date 类的使用: 使用 Date 类的默 ...

最新文章

  1. 1108. Defanging an IP Address
  2. python凯撒密码详解_Python基础题目集--课堂案例
  3. dm7和mysql_【干货分享】达梦数据库DM7的新特性发布啦
  4. 用C语言写的万年历---亲手写的。好累哦
  5. 【转】MATLAB的polar函数 极坐标绘制最大半径怎样设置
  6. Android的intent之间复杂参数的传递
  7. 避免流量高峰期CDN问题的10个方法
  8. PotPlayer:最强播放器,无边框
  9. 如何在Node.js中打印堆栈跟踪?
  10. 解决数据倾斜一:RDD执行reduceByKey或则Spark SQL中使用group by语句导致的数据倾斜
  11. 014基于SSH航空订票系统air
  12. 挪威议会邮件系统遭遇攻击,电子邮件安全该如何保障?
  13. 武汉芯源CW32L083系列MCU在空气净化器的应用介绍
  14. 七段数码显示管—设计报告,visio图,Multisim仿真
  15. 为什么巡检在工业生产中如此重要?
  16. c# Stack源码解析
  17. 市场营销环境分析的方法
  18. 《桃花庵歌》——唐伯虎
  19. 基于Echarts实现可视化数据大屏分析大屏监控系统
  20. java实习经验与总结建议

热门文章

  1. 阶段3 2.Spring_07.银行转账案例_5 编写业务层和持久层事务控制代码并配置spring的ioc...
  2. Maven依赖下载速度慢,不用怕,这么搞快了飞起
  3. MemCache在Windows下环境的搭建及启动
  4. Python星号表达式
  5. ChainOfResponsibilityPattern(23种设计模式之一)
  6. 分享一个前辈的NPOIhelper
  7. codeforces 597C (树状数组+DP)
  8. 【第四章】 资源 之 4.3 访问Resource ——跟我学spring3
  9. sharepoint 2007,sharepoint 2010网站的备份还原
  10. BUAA_OO_第一次作业总结