【发布时间】: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