天天看點

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