关于 java:如何修复这种将字符串中的数字转换为显示正确的小数位数的方法? | 珊瑚贝

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


我有以下问题。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * @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;
}

例如,如果我调用类似:

1
utilityClass.getFormattedNumber(57.4567, null,“,”, 2)

我得到字符串 57,45

好的,这很好。

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

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

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


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


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

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

DecimalFormat 的 Java 文档


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

1
#,###,###.##

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

1
#,###,###.00

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

  • 嗯,我该如何为我的方法设置此设置?
  • 由于您已经收到十进制位数作为数字,因此 Aestel 给出的答案更合适。


来源:https://www.codenong.com/27508174/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8766.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?