Java Numeric Formatting--reference

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

时间: 2024-10-12 00:56:37

Java Numeric Formatting--reference的相关文章

《Java: The Complete Reference》《Java 8 编程参考官方教程(第9版)》读书笔记

春节期间读了下<Java: The Complete Reference>发现这本书写的深入浅出,我想一个问题,书中很多内容我们也知道,但是为什么我们就写不出这样一本书,这么全面,这么系统,这么简单易懂.不得不佩服Herbert Schildt的编程功底,需要提到的是Herbert Schildt写了很多Java和C.C++的书,他是C.C++.Java和C#编程语言的权威,是ANSI/ISO组织C语言标准化委员会的委员. Herbert Schildt最新的基本Java著作其实都差不多,在内

Java Stream &amp; Method Reference

目录 Java Stream & Method Reference 1. Stream流 1.1 概述 1.2 流式思想的概述 1.3 获取流 1.4 常用方法 1.5 练习:集合元素处理(传统方式) 1.6 练习:集合元素处理(Stream流方式) 2. 方法引用 2.1 基本介绍 2.2 通过对象名引用[成员方法] 2.3 通过类名称引用[静态方法] 2.4 通过super引用父类的普通成员方法 2.5 通过this引用本类的普通成员方法 2.6 类的构造器(构造方法)引用 2.7 数组的构

java.lang.ref.Reference&lt;T&gt;

//看之前先要知道java里面的四种引用.package com.zby.ref; import sun.misc.Cleaner; /** * 引用对象的抽象基础类.这个类定义了所有引用对象的公共操作.因为引用对象在跟垃圾收集器紧密合作中被实现,所以这个类不能被引用对象直接继承. * * @author zhoubaiyun * * @param <T> */ public abstract class Reference<T> { /* * 一个引用实例是在这四个可能的内部状态

java中的Reference抽象类

一.概述 位于java.lang.ref包下,声明:public abstract class Reference<T> extends Object 引用对象的抽象基类.此类定义了常用于所有引用对象的操作.因为引用对象是通过与垃圾回收器的密切合作来实现的,所以不能直接为此类创建子类. 二.方法详细 1.public T get()  返回此引用对象的指示对象.如果此引用对象已经由程序或垃圾回收器清除,则此方法将返回 null. 2.public void clear()  清除此引用对象.调

java中的Reference

这两天又重新学习了一下Reference,根据网上的资源做了汇总. Java中的引用主要有4种: 强引用 StrongReference: Object obj = new Object(); obj就为一个强引用,obj=null后, 该对象可能会被JVM回收 软引用 SoftReference: 在内存不够用的时候,才会回收软引用的对象. Object obj = new Object(); SoftReference<Object> softref = new SoftReference

理解java reference

Java世界泰山北斗级大作<Thinking In Java>切入Java就提出“Everything is Object”.在Java这个充满Object的世界中,reference是一切谜题的根源,所有的故事都是从这里开始的. Reference是什么? 如果你和我一样在进入Java世界之前曾经浪迹于C/C++世界,就一定不会对指针陌生.谈到指针,往日种种不堪回首的经历一下子涌上心头,这里不是抱怨的地方,让我们暂时忘记指针的痛苦,回忆一下最初接触指针的甜蜜吧!还记得你看过的教科书中,如何讲

Java Secure Socket Extension (JSSE) Reference Guide

Skip to Content Oracle Technology Network Software Downloads Documentation Search Java Secure Socket Extension (JSSE) Reference Guide This guide covers the following topics: Skip Navigation Links Introduction Features and Benefits JSSE Standard API S

thinking in java 之Reference类的使用

Reference是java中的特殊引用类.描述的是特殊作用(主要是关于垃圾回收对象)的引用. 它有3个子类: 1.SoftReference; 2.WeakReference 3.PhantomReference 先看thinking in java 中的实例 package containers; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.Refere

java中的4种reference的差别和使用场景(含理论、代码和执行结果)

我们知道java语言提供了4种引用类型:强引用.软引用(SoftReference).弱引用(WeakReference)和幽灵引用(PhantomReference),与引用密切相关的,还有一个引用队列ReferenceQueue.引用和引用队列的关系,对于垃圾回收来说非常重要,学习垃圾回收机制,必须要先了解引用和引用队列的使用方法.本文主要参考网上的一些理论,同时配合自己的一些测试代码,更好的理解这些概念.这篇博客也解决了 System.gc()和-XX:+DisableExplicitGC