How to use the NumberFormat class and DecimalFormat class in Java?

NumberFormat and DecimalFormat are two classes in Java used for formatting numbers.

The NumberFormat class is an abstract class used for formatting and parsing numbers. You can obtain a default NumberFormat object by calling the static method getInstance(), or obtain a specific type of NumberFormat object by calling static methods like getCurrencyInstance() or getPercentInstance(). You can then use the format() method to format numbers into strings, and the parse() method to parse strings into numbers.

The DecimalFormat class is a specific subclass of NumberFormat used to format and parse decimal numbers. By creating a DecimalFormat object, setting the formatting pattern, and then calling the format() method, numbers can be formatted as strings and parsed back to numbers using the parse() method.

Here is an example code demonstrating how to format numbers using the NumberFormat class and DecimalFormat class.

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
    public static void main(String[] args) {
        // 使用NumberFormat类格式化数字
        NumberFormat numberFormat = NumberFormat.getInstance();
        String formattedNumber = numberFormat.format(12345.67);
        System.out.println("Formatted number: " + formattedNumber);
        
        // 使用DecimalFormat类格式化数字
        DecimalFormat decimalFormat = new DecimalFormat("#,###.00");
        String formattedDecimal = decimalFormat.format(12345.67);
        System.out.println("Formatted decimal: " + formattedDecimal);
        
        // 使用DecimalFormat类解析字符串
        try {
            Number parsedNumber = decimalFormat.parse("12,345.67");
            System.out.println("Parsed number: " + parsedNumber);
        } catch (Exception e) {
            System.out.println("Error parsing number");
        }
    }
}

In the example above, we initially used the NumberFormat class and DecimalFormat class to format a number and a decimal number separately, and printed the results. Then we used the DecimalFormat class to parse a formatted string and printed the result.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds