溫馨提示×

java中numberformat的用法是什么

小億
105
2023-12-27 20:12:32
欄目: 編程語言

NumberFormat類是Java中用于格式化數(shù)字的類。它提供了一些靜態(tài)方法和實例方法來格式化和解析數(shù)字。

  1. 使用靜態(tài)方法獲取NumberFormat實例:

    • getInstance():返回當前默認語言環(huán)境的通用數(shù)值格式器。
    • getCurrencyInstance():返回當前默認語言環(huán)境的通用貨幣格式器。
    • getPercentInstance():返回當前默認語言環(huán)境的通用百分比格式器。
  2. 實例方法:

    • setMaximumIntegerDigits(int newValue):設置最大整數(shù)位數(shù)。
    • setMinimumIntegerDigits(int newValue):設置最小整數(shù)位數(shù)。
    • setMaximumFractionDigits(int newValue):設置最大小數(shù)位數(shù)。
    • setMinimumFractionDigits(int newValue):設置最小小數(shù)位數(shù)。
    • setGroupingUsed(boolean newValue):設置是否啟用分組(千位分隔符)。
    • format(double/long/Number number):將數(shù)字格式化為字符串。
    • parse(String source):將字符串解析為數(shù)字。

示例代碼:

import java.text.NumberFormat;

public class NumberFormatExample {
    public static void main(String[] args) {
        double number = 12345.6789;

        // 獲取通用數(shù)值格式器
        NumberFormat numberFormat = NumberFormat.getInstance();
        String formattedNumber = numberFormat.format(number);
        System.out.println("通用格式化:" + formattedNumber);

        // 獲取貨幣格式器
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
        String formattedCurrency = currencyFormat.format(number);
        System.out.println("貨幣格式化:" + formattedCurrency);

        // 獲取百分比格式器
        NumberFormat percentFormat = NumberFormat.getPercentInstance();
        String formattedPercent = percentFormat.format(number);
        System.out.println("百分比格式化:" + formattedPercent);

        // 解析字符串為數(shù)字
        String source = "12,345.6789";
        try {
            double parsedNumber = numberFormat.parse(source).doubleValue();
            System.out.println("解析結果:" + parsedNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

輸出結果:

通用格式化:12,345.679
貨幣格式化:¥12,345.68
百分比格式化:1,234,568%
解析結果:12345.679

通過NumberFormat類,可以方便地對數(shù)字進行格式化和解析,以滿足不同的顯示需求。

0