DecimalFormat的使用

来源:互联网 发布:淘宝不能支付怎么回事 编辑:程序博客网 时间:2024/05/01 08:32
转载:http://www.blogjava.net/zhanglijun33/archive/2007/08/03/java2.html
 
   用 DecimalFormat 格式化数字引言 Java中对浮点数的输出表示在Java中浮点数包括基本型float、double,以及对象包装类型的Float和Double,对于这些浮点数的输出,不管是显式地还是隐式地调用toString()得到它的表示字串,输出格式都是按照如下规则进行的如果绝对值大于0.001、小于10000000,那么就以常规的小数形式表示。如果在上述范围之外,则使用科学计数法表示。即类似于1.234E8的形式。可以使用 java.text.DecimalFormat及其父类NumberFormat格式化数字本例只浅述DecimalFormat的使用。 Pattern 0 - 如果对应位置上没有数字,则用零代替 # - 如果对应位置上没有数字,则保持原样(不用补);如果最前、后为0,则保持为空。正负数模板用分号(;)分割 Number Format Pattern Syntax You can design your own format patterns for numbers by following the rules specified by the following BNF diagram: pattern := subpattern{;subpattern} subpattern := {prefix}integer{.fraction}{suffix} prefix := '//u0000'..'//uFFFD' - specialCharacters suffix := '//u0000'..'//uFFFD' - specialCharacters integer := '#'* '0'* '0' fraction := '0'* '#'* DEMO value 123456.789 pattern ,###.### output 123,456.789 Explanation 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. 井号(#)表示一位数字,逗号是用于分组分隔符的占位符,点是小数点的占位符。如果小数点的右面,值有三位,但是式样只有两位。format方法通过四舍五入处理。 value 123.78 pattern 000000.000 output 000123.780 Explanation The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#). 应用实例 1: /* * Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved. */ import java.util.*; 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 localizedFormat(String pattern, double value, Locale loc ) { NumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); String output = df.format(value); System.out.println(pattern + " " + output + " " + loc.toString()); } static public void main(String[] args) { customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); customFormat("/u00a5###,###.###", 12345.67); Locale currentLocale = new Locale("en", "US"); DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale); unusualSymbols.setDecimalSeparator('|'); unusualSymbols.setGroupingSeparator('^'); String strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4); String bizarre = weirdFormatter.format(12345.678); System.out.println(bizarre); Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"), new Locale("fr", "FR") }; for (int i = 0; i
posted on