小数格式模式

发布于 2024-12-20 22:51:51 字数 667 浏览 6 评论 0原文

public static String formatAmountUpToTwoDecimalNumber(String amount)
    {       
        if(amount==null || "".equals(amount))
        {
             return "";
        }  
        Double doubleAmount = Double.valueOf(amount);
        double myAmount = doubleAmount.doubleValue();
        NumberFormat f = new DecimalFormat("###,###,###,###,##0.00");
        String s = f.format(myAmount);
        return s;
    }

"###,###,###,###,##0.00",这个模式的目的到底是什么?我相信它对数字进行分组有两个目的

  1. ,那就是
  2. 在小数点后添加千位分隔符逗号,如果缺少小数点,则将 23 转换为 23.00

但为什么有 "0" 而不是 小数点前的“#”?这个零的具体目的是什么? 感谢您的帮助。

public static String formatAmountUpToTwoDecimalNumber(String amount)
    {       
        if(amount==null || "".equals(amount))
        {
             return "";
        }  
        Double doubleAmount = Double.valueOf(amount);
        double myAmount = doubleAmount.doubleValue();
        NumberFormat f = new DecimalFormat("###,###,###,###,##0.00");
        String s = f.format(myAmount);
        return s;
    }

"###,###,###,###,##0.00", What exactly is the purpose of this pattern ? I believe it serves two purposes

  1. to group numbers, that is put thousand seperator comma
  2. to append two zeros after decimal if decimal is missing that is convert 23 to 23.00

But why there is "0" instead of "#" before decimal? what exactly is the purpose of this zero?
Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情独悲 2024-12-27 22:51:51
Symbol  Location    Localized?  Meaning
0       Number      Yes         Digit
#       Number      Yes         Digit, zero shows as absent 

来自: http://docs.oracle.com/javase /7/docs/api/java/text/DecimalFormat.html

因此,当没有数字时,不会显示#。前导 0 表示小数点分隔符之前至少有 1 位数字。

Symbol  Location    Localized?  Meaning
0       Number      Yes         Digit
#       Number      Yes         Digit, zero shows as absent 

From: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

So # is not shown when there is no number. The leading 0 means there will be at least 1 digit before the decimal separator.

故人如初 2024-12-27 22:51:51

# 仅当数字不是前导零时才会输入数字。 0 将输入一个数字,即使它是尾随零。如果您想打印固定数量的数字,也可以在前面使用零。

# will put a digit only if it is not a leading zero. 0 will put a digit even if it is a trailing zero. You could use zeros in front, too, if you wanted a fixed number of digits printed.

初心 2024-12-27 22:51:51

如果 dp 前面有零,像 0.23 这样的小数字将显示为 0.23。如果没有它,您将无法获得前导零,因此它仅显示为 0.23。如果您有 Excel 之类的电子表格,也可以在那里检查。

With the zero before the dp, small numbers like 0.23 will be displayed as 0.23. Without it you will not get the leading zero, so it is just displayed as .23. If you have a spreadsheet like excel you can check this there too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文