Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set space separator to float DecimalFormat?

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?

like image 857
Saibamen Avatar asked Feb 10 '15 12:02

Saibamen


2 Answers

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.

like image 87
JohnEye Avatar answered Sep 23 '22 02:09

JohnEye


Ok I got what I want :)

new DecimalFormat("###,###.#").format(fIncome)
like image 25
Saibamen Avatar answered Sep 21 '22 02:09

Saibamen