如何在java中转义DecimalFormat模式符号

时间:2017-09-06 12:18:07

标签: java decimalformat

我想用DecimalFormat模式符号格式化数字。有什么想法吗?

Ex:### 123美元和00美分###

其中123需要使用DecimalFormat.format方法格式化

在C#中,可以使用escape(" \")字符。 java中有没有类似的方法?

double value = 123;
Console.WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#"));

先谢谢

2 个答案:

答案 0 :(得分:0)

只需将字符连接到字符串的开头和结尾。

System.out.println("### " & formattedString & " ###")

无论如何,它更具可读性。

答案 1 :(得分:0)

您可以执行以下操作:

String pattern = "###,###,### Dolars ";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
System.out.println("###" + decimalFormat.format(123456789) + "00 cents ###");

但是你不能以二分法写下XX美分。

这可能是一种解决方法,但它仍然很难看:

String pattern = "###,###,###.###";
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('$');
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.format(123456789.123) + " cents");

打印

123.456.789$123 cents.