欢迎访问宙启技术站
智能推送

Java函数实现对数字的格式化和转换

发布时间:2023-10-02 12:29:48

在Java中,可以使用DecimalFormat类来实现数字的格式化和转换。以下是使用DecimalFormat类的示例代码:

import java.text.DecimalFormat;

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

        // 格式化为保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        String formattedNumber = decimalFormat.format(number);
        System.out.println("Formatted Number with 2 decimal places: " + formattedNumber);

        // 格式化为每三位添加千位分隔符
        decimalFormat = new DecimalFormat("#,###.##");
        formattedNumber = decimalFormat.format(number);
        System.out.println("Formatted Number with thousands separator: " + formattedNumber);

        // 格式化为百分数
        decimalFormat = new DecimalFormat("#%");
        formattedNumber = decimalFormat.format(number);
        System.out.println("Formatted Number as percentage: " + formattedNumber);

        // 将字符串转换为数字
        String numberString = "123456";
        int convertedNumber = Integer.parseInt(numberString);
        System.out.println("Converted Number from String: " + convertedNumber);

        // 将数字转换为字符串
        int numberValue = 7890;
        String stringValue = String.valueOf(numberValue);
        System.out.println("Converted String from Number: " + stringValue);
    }
}

输出结果为:

Formatted Number with 2 decimal places: 12345.68
Formatted Number with thousands separator: 12,345.68
Formatted Number as percentage: 1234567%
Converted Number from String: 123456
Converted String from Number: 7890

上述代码展示了几种常见的数字格式化操作。首先,使用DecimalFormat类可以指定要保留的小数位数,添加千位分隔符和格式化为百分数。而对于字符串到数字的转换,可以使用Integer.parseInt()方法将字符串转换为整数,或者使用String.valueOf()方法将数字转换为字符串。