如何使用Java的DecimalFormat进行“智能”货币格式化?
我想使用Java的DecimalFormat来格式化双打,如下所示:
#1 - 100 -> $100 #2 - 100.5 -> $100.50 #3 - 100.41 -> $100.41
到目前为止,我能想出的最好的是:
new DecimalFormat("'$'0.##");
但这不适用于案例#2,而是输出“$ 100.5”
编辑:
很多这些答案只考虑案例#2和#3而没有意识到他们的解决方案会导致#1将100格式化为“100.00美元”而不仅仅是“100美元”。
是否必须使用DecimalFormat
?
如果没有,看起来应该如下:
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber); //Handle the weird exception of formatting whole dollar amounts with no decimal currencyString = currencyString.replaceAll("\\.00", "");
使用NumberFormat:
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); double doublePayment = 100.13; String s = n.format(doublePayment); System.out.println(s);
另外,请勿使用双精度来表示精确值。 如果您在蒙特卡罗方法中使用货币值(其中值无论如何都不准确),则首选双倍。
另请参阅: 编写Java程序以计算和格式化货币
尝试
new DecimalFormat("'$'0.00");
编辑:
我试过了
DecimalFormat d = new DecimalFormat("'$'0.00"); System.out.println(d.format(100)); System.out.println(d.format(100.5)); System.out.println(d.format(100.41));
得到了
$100.00 $100.50 $100.41
尝试使用
DecimalFormat.setMinimumFractionDigits(2); DecimalFormat.setMaximumFractionDigits(2);
您可以选中“是否为全数”并选择所需的数字格式。
public class test { public static void main(String[] args){ System.out.println(function(100d)); System.out.println(function(100.5d)); System.out.println(function(100.42d)); } public static String function(Double doubleValue){ boolean isWholeNumber=(doubleValue == Math.round(doubleValue)); DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN); formatSymbols.setDecimalSeparator('.'); String pattern= isWholeNumber ? "#.##" : "#.00"; DecimalFormat df = new DecimalFormat(pattern, formatSymbols); return df.format(doubleValue); } }
会给出你想要的东西:
100 100.50 100.42
您可以使用以下格式:
DecimalFormat dformat = new DecimalFormat(“$#。##”);
我知道为时已晚。 然而,以下为我工作:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK); new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale); \u00A4 : acts as a placeholder for currency symbol #######0.00 : acts as a placeholder pattern for actual number with 2 decimal places precision.
希望这能帮助将来读这个的人:)
您可以根据条件尝试使用两个不同的DecimalFormat
对象,如下所示:
double d=100; double d2=100.5; double d3=100.41; DecimalFormat df=new DecimalFormat("'$'0.00"); if(d%1==0){ // this is to check a whole number DecimalFormat df2=new DecimalFormat("'$'"); System.out.println(df2.format(d)); } System.out.println(df.format(d2)); System.out.println(df.format(d3)); Output:- $100 $100.50 $100.41
printf也有效。
例:
double anyNumber = 100; printf(“值为%4.2f”,anyNumber);
输出:
值为100.00
4.2表示强制数字在小数点后有两位数。 4控制小数点右边的位数。