如果 result.doubleValue() 大于 100%,则将其设置为 100%。为了确保百分比结果始终在 0% 到 100% 之间,可以使用以下代码:

import java.text.DecimalFormat;

public class PercentageFormatter {
    public static void main(String[] args) {
        double result = 120.5;
        DecimalFormat percent = new DecimalFormat("0.0%");
        String formattedPercentage = percent.format(Math.min(result, 100));
        System.out.println(formattedPercentage); // 输出:100.0%
    }
}

代码解释:

  1. 使用 DecimalFormat 类创建 percent 对象,并设置格式为 "0.0%"。
  2. 使用 Math.min(result, 100) 获取 result 和 100 的最小值,确保结果不超过 100。
  3. 将最小值传递给 percent.format() 方法,以格式化为百分比字符串。
Java 格式化百分比:限制最大值为 100%

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

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