【问题标题】:Using DecimalFormat to format currency string in Java在 Java 中使用 DecimalFormat 格式化货币字符串
【发布时间】:2015-12-22 00:16:18
【问题描述】:

我需要获取一个包含双精度的字符串(类似于 14562.34)并将其格式化,使其看起来像 $000,000,00#.##-。我的意思是 $ 将一直向左,如果数字不存在,上面的 0 将不会显示,但我确实希望间距存在。 #s 将是数字,如果数字为零,我至少需要 0.00 才能显示出来。如果数字为负数,则“-”将显示(尽管我相信这是我可以在没有格式化程序的情况下最后添加的东西)。当我尝试为格式化程序执行“000,000,00#.##”时,我得到一个格式错误的异常。

有没有人有关于这样做或我做错了什么的提示?

以下是示例:

1234.56 -> $______1,234.56

0 -> $__________0.00

1234567.89 -> $__1,234,567.89

'_' 代表仍然存在的空间。

谢谢。

【问题讨论】:

标签: java currency decimalformat


【解决方案1】:
public static void main(String[] args) throws ParseException {
String data = "1234.6";
DecimalFormat df = new DecimalFormat("$0,000,000,000.00");
System.out.println( df.format(Double.parseDouble(data)));
}

注意“00”,意思是小数点后两位。

如果您使用“#.##”(# 表示“可选”数字),它将删除尾随零 - 即 new DecimalFormat("#.##").format(3.0d);只打印“3”,而不是“3.00”。

编辑:-

如果你想要空格而不是零,你可以使用 String.format() 方法来实现。 如果小数的大小大于最大前导零大小,则返回带美元符号的双解析数字,否则添加前导空格。

这里的长度是可以添加空格之前的最大大小,在该前导空格被忽略之后。

public static String leadingZeros(String s, int length) {
    if (s.length() >= length) return String.format("$%4.2f",Double.valueOf(s));
    else 
        return String.format("$%" + (length-s.length()) + "s%1.2f",  " ",Double.valueOf(s));
    } 

【讨论】:

  • 更新了前导空格而不是前导零的答案。
【解决方案2】:

如果您正在寻找有关如何根据数字格式化货币的详细信息...这是确保数字货币显示正确的区域设置和格式的最佳方式。

public String getFormattedCurrencyValue(String number){

   BigDecimal num = new BigDecimal(number);
   NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
   Currency currency = nf.getCurrency();

   String str = StringUtil.replace(
            nf.format(number),
            nf.getCurrency().getSymbol(locale),
            "",false).trim();

   return currency.getCurrencyCode()+str;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多