How to set space separator to float DecimalFormat?

▼魔方 西西 提交于 2020-04-10 18:46:31

问题


How to set space as thousand separator for DecimalFormat in float? I want to show 13,52 as 13,5, but 13,00 as 13 and I did this with

new DecimalFormat("#.#").format(fIncome)

but I want to 1400,5 be 1 400,5 and 1400 to be 1 400.

For double I use this code (I don't want to shows numbers after comma in dCount):

String.format("%,d", (int)dCount)

But how to use this for floating number with 1 number after comma?


回答1:


The accepted answer probably lacks a few lines of code, because it doesn't work as described. Here's how I did it:

private static final String DECIMAL_FORMAT = "###,###.#";

private String formatValue(Number value, String formatString) {
        DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
        formatSymbols.setDecimalSeparator('.');
        formatSymbols.setGroupingSeparator(' ');
        DecimalFormat formatter = new DecimalFormat(formatString, formatSymbols);
        return formatter.format(value);
    }

I then call it like this:

formatValue(value, DECIMAL_FORMAT);

To explain how it works, the . in DECIMAL_FORMAT is replaced with decimalSeparator and the , is replaced with groupingSeparator, which is a space in this case.




回答2:


Ok I got what I want :)

new DecimalFormat("###,###.#").format(fIncome)


来源:https://stackoverflow.com/questions/28432122/how-to-set-space-separator-to-float-decimalformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!