可以使用 NumberFormat 类来实现保留两位小数的功能。以下是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        double num1 = 3.14159;
        double num2 = 2.71828;

        double percentage = (num1 / num2) * 100;

        NumberFormat formatter = new DecimalFormat('#0.00');
        String formattedPercentage = formatter.format(percentage);

        System.out.println('百分比: ' + formattedPercentage + '%');
    }
}

输出结果为:

百分比: 115.56%

在代码中,DecimalFormat('#0.00') 表示保留两位小数的格式,通过调用 format() 方法将百分比值格式化为字符串。

Java 8 计算两个数的百分比并保留两位小数

原文地址: https://www.cveoy.top/t/topic/mYxl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录