Java 数字格式化 笔记
2012-04-12 13:43 java环境变量 阅读(253) 评论(0) 收藏 举报//java数字格式化. DecimalFormat类的学习
//有两种实现数字格式化的方式. 一是直接在创建对象时传递格式. 二是利用 类中 applyPattern方法传递格式.
import java.text.DecimalFormat;
public class DecimalFormatDemo {
static public void SimpleFormat(String pattern, double value){ //直接设置格式.
DecimalFormat myFormat = new DecimalFormat(pattern);
String output = myFormat.format(value);
System.out.println(value + " 格式: " + pattern + " 结果: " + output);
}
static public void UseApplyPatternFormat(String pattern, double value){
DecimalFormat myFormat = new DecimalFormat();
myFormat.applyPattern(pattern); //用 applyPattern 方法设置格式.
String output = myFormat.format(value);
System.out.println(value + " 格式: " + pattern + " 结果: " + output);
}
public static void main(String[] args) {
double testValue=123456.789;
SimpleFormat("###,###.###", testValue); //"#" 表示一位数字. 该位存在显示,不存在不显示.
// 123456.789 ###,###.### 123,456.789
SimpleFormat("###,#.###", testValue); //为什么是这个结果 .逗号前不是 三位的数字吗? 求解释 .
// 123456.789 ###,#.### 1,2,3,4,5,6.789
UseApplyPatternFormat("###.##", testValue);
//123456.789 格式: ###.## 结果: 123456.79
SimpleFormat("-####.###kg", testValue); //"-" 负号
// 123456.789 格式: -####.###kg 结果: -123456.789kg
SimpleFormat("0.000", testValue); //"0" 表示一位数字,该位存在数字 则显示 ,不存在显示0. // 123456.789 格式: 0.000 结果: 123456.789
SimpleFormat("###,#.000", testValue);
// 123456.789 格式: ###,#.000 结果: 1,2,3,4,5,6.789
SimpleFormat("0.0E00", testValue); //"E" 将数字用科学计数法表示
//123456.789 格式: 0.0E00 结果: 1.2E05
UseApplyPatternFormat("#.###%", testValue); //"%" 将数字乘100显示 百分数.
//123456.789 格式: #.###% 结果: 12345678.9%
UseApplyPatternFormat("0.00\u2030", testValue); //"\u2030" 将数字乘1000显示 千分数.
//123456.789 格式: 0.00‰ 结果: 123456789.00‰
UseApplyPatternFormat("0.000\u00A4", testValue); //"\u00A4" 货币符号.
// 123456.789 格式: 0.000¤ 结果: 123456.789¥
}
}
浙公网安备 33010602011771号