How is the NumberFormat used in Java?

The NumberFormat class in Java is used for formatting numbers, providing static and instance methods for formatting and parsing numbers.

  1. Retrieve NumberFormat instance using static methods.
  2. getInstance(): Returns a general number formatter for the current default language environment.
  3. getCurrencyInstance() returns a general currency formatter for the current default locale.
  4. getPercentInstance(): returns a general percentage formatter for the current default language environment.
  5. Example methods:
  6. setMaxIntegerDigits(int newValue): Set the maximum number of integer digits.
  7. setMinimumIntegerDigits(int newValue): Specify the minimum number of integer digits.
  8. Set maximum number of decimal places.
  9. setMinimumFractionDigits(int newValue): sets the minimum number of decimal places.
  10. setGroupingUsed(boolean newValue): enable/disable grouping (thousands separator).
  11. format(double/long/Number number): Convert a number into a formatted string.
  12. parse(String source): parse the string into a number.

Example code:

import java.text.NumberFormat;

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

        // 获取通用数值格式器
        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);

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

Output result:

通用格式化:12,345.679
货币格式化:¥12,345.68
百分比格式化:1,234,568%
解析结果:12345.679

The NumberFormat class makes it easy to format and parse numbers in order to meet various display requirements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds