天天看点

Java 数字格式化 DecimalFormat

今天写代码的时候,需要对计算后的数剧格式化,google 发现 Java 提供的 DecimalFormat 类可以很方便的进行此类操作。

DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。

0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置

java 7 注释:

DecimalFormat is a concrete subclass of NumberFormat that formats

decimal numbers. It has a variety of features designed to make it

possible to parse and format numbers in any locale, including support

for Western, Arabic, and Indic digits. It also supports different

kinds of numbers, including integers (123), fixed-point numbers

(123.4), scientific notation (1.23E4), percentages (12%), and currency

amounts ($123). All of these can be localized.

下面的例子包含了常见的应用场景,保存一下。

public static void main(String[] args) {
        double pi = ; // 圆周率
        // 取一位整数
        System.out.println(new DecimalFormat("0").format(pi));// 3
        // 取一位整数和两位小数
        System.out.println(new DecimalFormat("0.00").format(pi));// 3.14
        // 取两位整数和三位小数,整数不足部分以0填补。
        System.out.println(new DecimalFormat("00.000").format(pi));// 03.142
        // 取所有整数部分
        System.out.println(new DecimalFormat("#").format(pi));// 3
        // 以百分比方式计数,并取两位小数
        System.out.println(new DecimalFormat("#.##%").format(pi));// 314.16%

        long c = ;// 光速
        // 显示为科学计数法,并取五位小数
        System.out.println(new DecimalFormat("#.#####E0").format(c));// 2.99792E8
        // 显示为两位整数的科学计数法,并取四位小数
        System.out.println(new DecimalFormat("00.####E0").format(c));// 29.9792E7
        // 每三位以逗号进行分隔。
        System.out.println(new DecimalFormat(",###").format(c));// 299,792,458
        // 将格式嵌入文本
        System.out.println(new DecimalFormat("光速大小为每秒,###米。").format(c));
    }
           

参考 : http://blog.csdn.net/wangchangshuai0010/article/details/8577982