2015-12-22 88 views
-1

我需要一个包含double(类似于14562.34)的字符串并对其进行格式化,使其看起来像$ 000,000,00#。## - 。我的意思是,$将一路左移,如果一个数字不在那里,上面的0不会出现,但我希望间隔在那里。 #是数字,如果数字为零,我需要至少0.00才显示出来。如果数字是负数,' - '会显示出来(尽管我相信这是我在格式化程序的最后可以做的)。当我尝试为格式化程序执行“000,000,00#。##”时,我得到格式错误的异常。使用DecimalFormat在Java中格式化货币字符串

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

下面举例说明:

1234.56 - > $ ______ 1,234.56

0 - > $ 0.00 __________

1234567.89 - > $ __ 1,234,567.89

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

谢谢。

+0

我认为这个问题回答你在找什么[使用BigDecimal的(http://stackoverflow.com/questions/13791409/java-format-double-value-as-dollar-amount) –

+2

可能的复制与货币工作](http://stackoverflow.com/questions/1359817/using-bigdecimal-to-work-with-currencies) – Abdelhak

回答

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”,意思是两位小数。如果您使用“#。##”(#表示“可选”数字),它将删除尾随零 - 即新的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)); 
    } 
+1

更新的领先空间答案,而不是领先零。 – Naruto

0

如果你正在寻找如何从一个数字格式的货币细节......这是为了确保您的数字货币显示了正确的语言环境和格式的最佳方式。

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; 
}