繁体   English   中英

如何解决将String中的Number转换为正确的十进制数字的方法?

[英]How can I fix this method that convert Number in String to show the correct number of decimal digits?

我有以下问题。

我正在使用此方法将Number(作为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此方法的输入参数中的小数位数)

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

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

尝试设置最小分数位数和最大分数位数。

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

适用于DecimalFormat的Java文档

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

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

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

#,###,###.00

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM