【问题标题】:How can I fix this method that convert Number in String to show the correct number of decimal digits?如何修复这种将字符串中的数字转换为显示正确的小数位数的方法?
【发布时间】:2015-02-14 23:21:35
【问题描述】:

我有以下问题。

我正在使用这种方法将数字(作为 BigDecimal)转换为格式化字符串:

/**
 * @param n il Number da formattare
 * @param thou_sep separator for hundreds
 * @param dec_sep  separator for decimal digits
 * @param number of decimal digits to show
 * @return a string representing the number
 * @author Andrea Nobili
 */
public static String getFormattedNumber(Number n, String thou_sep, String dec_sep, Integer decimalDigits) {

    if (n == null) return "";

    double value = n.doubleValue();

    if (decimalDigits != null && decimalDigits < 0)
        throw new IllegalArgumentException("[" + decimalDigits + " < 0]");

    DecimalFormatSymbols s = new DecimalFormatSymbols();
    if (thou_sep != null && thou_sep.length() > 0) {
        s.setGroupingSeparator(thou_sep.charAt(0));
    }
    if (dec_sep != null && dec_sep.length() > 0) {
        s.setDecimalSeparator(dec_sep.charAt(0));
    }
    DecimalFormat f = new DecimalFormat();
    f.setDecimalFormatSymbols(s);
    if (thou_sep == null || thou_sep.length() == 0) {
        f.setGroupingUsed(false);
    }
    if (decimalDigits != null) {
        f.setMaximumFractionDigits(decimalDigits);
    }
    f.setMaximumIntegerDigits(Integer.MAX_VALUE);
    String formattedNumber = f.format(value);
    return ("-0".equals(formattedNumber)) ? "0" : formattedNumber;
}

例如,如果我这样称呼:

utilityClass.getFormattedNumber(57.4567, null, ",", 2)

我得到字符串57,45

好的,这很好。

我的问题是,如果我尝试使用没有十进制数字的数字执行它(例如传递值 57,它会返回字符串 57。我想要那个在这种情况下,它返回字符串 57.00 (因为我已经指定我想要在这个方法的输入参数中包含 2 个十进制数字)

如何解决此问题并获得正确的小数位数?

【问题讨论】:

  • 这是一个学校项目吗?如果没有,请停止浪费您的时间并使用NumberFormat。如果是,请告诉我们,我们可以尝试指导您修复代码。

标签: java decimal bigdecimal


【解决方案1】:

您可以使用 DecimalFormat setMinimumFractionDigits 并将其设置为与最大值相同。

【讨论】:

    【解决方案2】:

    对于 DecimalFormat,您可以使用需要模式的构造函数。在您的模式中,# 符号表示零或如果不需要打印零(如小数点后)则为空白。如果要打印零,则将# 替换为0。例如:

    #,###,###.##
    

    仅在需要 0.54 或 0.3 但不是整数时才显示零。

    #,###,###.00
    

    将显示最多 2 位小数的尾随零,例如 2.50 或 79.00。

    【讨论】:

    • 嗯,我该如何为我的方法设置此设置?
    • 既然你已经收到了十进制位数作为数字,那么 Aestel 给出的答案更合适。
    【解决方案3】:

    尝试设置最小小数位数以及最大小数位数。

    f.setMaximumFractionDigits(decimalDigits);
    f.setMinimumFractionDigits(decimalDigits);
    

    Java Doc for DecimalFormat

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2021-05-30
      • 1970-01-01
      • 2015-08-25
      • 2023-03-27
      • 2016-07-31
      • 2023-04-08
      相关资源
      最近更新 更多