I can think of numerous times when I have seen others write unnecessary Java code and I have written unnecessary Java code because of lack of awareness of a JDK class that already provides the desired functionality. One example of this is the writing of time-related constants using hard-coded values such as 60241440, and 86400when TimeUnit provides a better, standardized approach. In this post, I look at another example of a class that provides the functionality I have seen developers often implement on their one: NumberFormat.

The NumberFormat class is part of the java.text package, which also includes the frequently used DateFormat and SimpleDateFormat classes. NumberFormat is an abstract class (no public constructor) and instances of its descendants are obtained via overloaded static methods with names such as getInstance()getCurrencyInstance(), and getPercentInstance().

Currency

The next code listing demonstrates calling NumberFormat.getCurrencyInstance(Locale)to get an instance of NumberFormat that presents numbers in a currency-friendly format.

Demonstrating NumberFormat's Currency Support

01./**
02.* Demonstrate use of a Currency Instance of NumberFormat.
03.*/ 
04.public void demonstrateCurrency() 
05.
06.writeHeaderToStandardOutput("Currency NumberFormat Examples"); 
07.final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); 
08.out.println("15.5      -> " + currencyFormat.format(15.5)); 
09.out.println("15.54     -> " + currencyFormat.format(15.54)); 
10.out.println("15.345    -> " + currencyFormat.format(15.345));  // rounds to two decimal places 
11.printCurrencyDetails(currencyFormat.getCurrency()); 
12.
13. 
14./**
15.* Print out details of provided instance of Currency.
16.*
17.* @param currency Instance of Currency from which details
18.*    will be written to standard output.
19.*/ 
20.public void printCurrencyDetails(final Currency currency) 
21.
22.out.println("Concurrency: " + currency); 
23.out.println("\tISO 4217 Currency Code:           " + currency.getCurrencyCode()); 
24.out.println("\tISO 4217 Numeric Code:            " + currency.getNumericCode()); 
25.out.println("\tCurrency Display Name:            " + currency.getDisplayName(Locale.US)); 
26.out.println("\tCurrency Symbol:                  " + currency.getSymbol(Locale.US)); 
27.out.println("\tCurrency Default Fraction Digits: " + currency.getDefaultFractionDigits()); 
28.}


When the above code is executed, the results are as shown next:

==================================================================================
= Currency NumberFormat Examples
==================================================================================
15.5 -> $15.50
15.54 -> $15.54
15.345 -> $15.35
Concurrency: USD
ISO 4217 Currency Code: USD
ISO 4217 Numeric Code: 840
Currency Display Name: US Dollar
Currency Symbol: $
Currency Default Fraction Digits: 2

The above code and associated output demonstrate that the NumberFormat instance used for currency (actually a DecimalFormat), automatically applies the appropriate number of digits and appropriate currency symbol based on the locale.

Percentages

The next code listings and associated output demonstrate use of NumberFormat to present numbers in percentage-friendly format.

Demonstrating NumberFormat's Percent Format

01./**
02.* Demonstrate use of a Percent Instance of NumberFormat.
03.*/ 
04.public void demonstratePercentage() 
05.
06.writeHeaderToStandardOutput("Percentage NumberFormat Examples"); 
07.final NumberFormat percentageFormat = NumberFormat.getPercentInstance(Locale.US); 
08.out.println("Instance of: " + percentageFormat.getClass().getCanonicalName()); 
09.out.println("1        -> " + percentageFormat.format(1)); 
10.// will be 0 because truncated to Integer by Integer division 
11.out.println("75/100   -> " + percentageFormat.format(75/100)); 
12.out.println(".75      -> " + percentageFormat.format(.75)); 
13.out.println("75.0/100 -> " + percentageFormat.format(75.0/100)); 
14.// will be 0 because truncated to Integer by Integer division 
15.out.println("83/93    -> " + percentageFormat.format((83/93))); 
16.out.println("93/83    -> " + percentageFormat.format(93/83)); 
17.out.println(".5       -> " + percentageFormat.format(.5)); 
18.out.println(".912     -> " + percentageFormat.format(.912)); 
19.out.println("---- Setting Minimum Fraction Digits to 1:"); 
20.percentageFormat.setMinimumFractionDigits(1); 
21.out.println("1        -> " + percentageFormat.format(1)); 
22.out.println(".75      -> " + percentageFormat.format(.75)); 
23.out.println("75.0/100 -> " + percentageFormat.format(75.0/100)); 
24.out.println(".912     -> " + percentageFormat.format(.912)); 
25.}


==================================================================================
= Percentage NumberFormat Examples
==================================================================================
1 -> 100%
75/100 -> 0%
.75 -> 75%
75.0/100 -> 75%
83/93 -> 0%
93/83 -> 100%
.5 -> 50%
.912 -> 91%
---- Setting Minimum Fraction Digits to 1:
1 -> 100.0%
.75 -> 75.0%
75.0/100 -> 75.0%
.912 -> 91.2%

The code and output of the percent NumberFormat usage demonstrate that by default the instance of NumberFormat (actually a DecimalFormat in this case) returned byNumberFormat.getPercentInstance(Locale) method has no fractional digits, multiplies the provided number by 100 (assumes that it is the decimal equivalent of a percentage when provided), and adds a percentage sign (%).

Integers

The small amount of code shown next and its associated output demonstrate use ofNumberFormat to present numbers in integral format.

Demonstrating NumberFormat's Integer Format

01./**
02.* Demonstrate use of an Integer Instance of NumberFormat.
03.*/ 
04.public void demonstrateInteger() 
05.
06.writeHeaderToStandardOutput("Integer NumberFormat Examples"); 
07.final NumberFormat integerFormat = NumberFormat.getIntegerInstance(Locale.US); 
08.out.println("7.65   -> " + integerFormat.format(7.65)); 
09.out.println("7.5    -> " + integerFormat.format(7.5)); 
10.out.println("7.49   -> " + integerFormat.format(7.49)); 
11.out.println("-23.23 -> " + integerFormat.format(-23.23)); 
12.}


==================================================================================
= Integer NumberFormat Examples
==================================================================================
7.65 -> 8
7.5 -> 8
7.49 -> 7
-23.23 -> -23

As demonstrated in the above code and associated output, the NumberFormat methodgetIntegerInstance(Locale) returns an instance that presents provided numerals as integers.

Fixed Digits

The next code listing and associated output demonstrate using NumberFormat to print fixed-point representation of floating-point numbers. In other words, this use ofNumberFormat allows one to represent a number with an exactly prescribed number of digits to the left of the decimal point ("integer" digits) and to the right of the decimal point ("fraction" digits).

Demonstrating NumberFormat for Fixed-Point Numbers

01./**
02.* Demonstrate generic NumberFormat instance with rounding mode,
03.* maximum fraction digits, and minimum integer digits specified.
04.*/ 
05.public void demonstrateNumberFormat() 
06.
07.writeHeaderToStandardOutput("NumberFormat Fixed-Point Examples"); 
08.final NumberFormat numberFormat = NumberFormat.getNumberInstance(); 
09.numberFormat.setRoundingMode(RoundingMode.HALF_UP); 
10.numberFormat.setMaximumFractionDigits(2); 
11.numberFormat.setMinimumIntegerDigits(1); 
12.out.println(numberFormat.format(234.234567)); 
13.out.println(numberFormat.format(1)); 
14.out.println(numberFormat.format(.234567)); 
15.out.println(numberFormat.format(.349)); 
16.out.println(numberFormat.format(.3499)); 
17.out.println(numberFormat.format(0.9999)); 
18.}


==================================================================================
= NumberFormat Fixed-Point Examples
==================================================================================
234.23
1
0.23
0.34
0.35
1

The above code and associated output demonstrate the fine-grain control of the minimum number of "integer" digits to represent to the left of the decimal place (at least one, so zero shows up when applicable) and the maximum number of "fraction" digits to the right of the decimal point. Although not shown, the maximum number of integer digits and minimum number of fraction digits can also be specified.

Conclusion

I have used this post to look at how NumberFormat can be used to present numbers in different ways (currency, percentage, integer, fixed number of decimal points, etc.) and often means no or reduced code need be written to massage numbers into these formats. When I first began writing this post, I envisioned including examples and discussion on the direct descendants of NumberFormat (DecimalFormat andChoiceFormat), but have decided this post is already sufficiently lengthy. I may write about these descendants of NumberFormat in future blog posts.

reference from:http://java.dzone.com/articles/java-numeric-formatting

Java Numeric Formatting--reference的更多相关文章

  1. Java引用机制——reference

    所谓引用传递就是指将堆内存空间的使用权交给多个栈内存空间. 例子<1> public class Aliasing { int temp = 30; public static void ...

  2. java中的Reference

    这两天又重新学习了一下Reference,根据网上的资源做了汇总. Java中的引用主要有4种: 强引用 StrongReference: Object obj = new Object(); obj ...

  3. java.lang.ref.Reference<T>

    //看之前先要知道java里面的四种引用.package com.zby.ref; import sun.misc.Cleaner; /** * 引用对象的抽象基础类.这个类定义了所有引用对象的公共操 ...

  4. Java中的Reference类使用

    Java 2 平台引入了 java.lang.ref 包,这个包下面包含了几个Reference相关的类,Reference相关类将Java中的引用也映射成一个对象,这些类还提供了与垃圾收集器(gar ...

  5. Does Java pass by reference or pass by value?(Java是值传递还是引用传递) - 总结

    这个话题一直是Java程序员的一个热议话题,争论不断,但是不论是你百度搜也好还是去看官方的文档中所标明的也好,得到的都只有一个结论:Java只有值传递. 在这里就不贴代码细致解释了,让我们来看看一些论 ...

  6. 你不可不知的Java引用类型之——Reference源码解析

    定义 Reference是所有引用类型的父类,定义了引用的公共行为和操作. reference指代引用对象本身,referent指代reference引用的对象,下文介绍会以reference,ref ...

  7. thinking in java 之Reference类的使用

    Reference是java中的特殊引用类.描述的是特殊作用(主要是关于垃圾回收对象)的引用. 它有3个子类: 1.SoftReference; 2.WeakReference 3.PhantomRe ...

  8. 理解java reference

    Java世界泰山北斗级大作<Thinking In Java>切入Java就提出“Everything is Object”.在Java这个充满Object的世界中,reference是一 ...

  9. java Reference(摘录)

    Java中的Reference对象和GC是紧密联系在一起的,Reference的实现也是和GC相关的. 强引用 强引用是Java中使用最普遍的引用,我们经常使用的Object o = new Obje ...

随机推荐

  1. AutoLayout(转)

    转自    http://blog.sina.com.cn/s/blog_9564cb6e0101wv9o.html controller和View的责任分配: 1.View指定固有的content  ...

  2. 高级I/O函数(3)-tee、fcntl函数

    tee函数使用 功能描述:tee函数在两个管道文件描述符之间复制数据,也是零拷贝操作.它不消耗数据,因此源文件描述符仍然可以用于后续的操作. 函数原型: #include <fcntl.h> ...

  3. 【NOIP2014】赛后总结

    noip考完了,心中所牵挂的一下子就消散了,感觉浑身很轻松. 说实话,我参加noip有好几次了,这应该会是我的最后一次,尽管如此,无论是在考试的前几天还是在考试的时候,心中都没有太多的紧张. 我在no ...

  4. 【HAOI2007】理想的正方形

    [问题描述] 有一个a*b的整数组成的矩阵,现请你从中找出一个n*n的正方形区域,使得该区域所有数中的最大值和最小值的差最小. [输入] 第一行为3个整数,分别表示a,b,n的值第二行至第a+1行每行 ...

  5. Qt信号槽连接在有默认形参下的情况思考

    写下这个给自己备忘,比如函数 ) 你在调用端如论是test(3)或者test(),都可以正确调用到这个函数. 但是,如果放到Qt中的信号槽的话,这个还是值得讲一讲的,不然的话,可能会引起相应的误会. ...

  6. 二分查找里的upper bound与lower bound的实现与分析

    1. 问题引入 最近参选了学堂在线的课程数据结构(2015秋).课程由清华大学的邓俊辉老师主讲,在完成课后作业时,遇到了这样一个题目范围查询.在这个题目中,我需要解决这样一个子问题:给定了一组已经排好 ...

  7. jQuery中自定义简单动画的实现

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  8. OOCSS学习(一)

    OOCSS —— 面向对象CSS 搜集一些该搜集的,然后汇总一下. 1.OOCSS 概念篇: 1)什么是面向对象 确定“对象”,并给这个对象创建CSS样式规则. 2)面向对象的CSS理论 OOCSS最 ...

  9. PHP图的绘制1

    最近在学习php图的绘制,写的代码放上来,供自己以后学习查看: <?php //*函数说明: //这个函数返回的是 // resource imagecreate ( int $x_size , ...

  10. poj Candies

    http://poj.org/problem?id=3159 #include<cstdio> #include<queue> #include<cstring> ...