Dimitri
Dimitri

Reputation: 687

Formatting double Android

I want to turn e.g. 5999.635554 to 5 999,63 . I used DecimalFormat method below:

public static String decimalDoubleForm(double value){

        DecimalFormat df = new DecimalFormat("#,###,###.00");
        String formatted_value = df.format(value).replaceAll("\\.", ",");

        return formatted_value;

}

However when i used it that is Util.decimalDoubleForm(value); on e.g. -4000.4343 i get the following -4,000,43.

my desired result should be -4000.4343 => -4 000,43.

Upvotes: 4

Views: 177

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

If you want -4,000.43 (the string from the format() call) to become -4 000,43, you can do two replacements.

The first is to replace all , characters with spaces, then replace all . characters with ,.

String formatted_value = df.format(value)
    .replaceAll(","  , " ")
    .replaceAll("\\.", ",");

That gets problematic when you want to swap , and . (a) but you can still do that, albeit with a 3-step process:

comma  => X
period => comma
X      => period

(where X is any character that otherwise doesn't appear in the string, like, for example, "X").

However, there may be a format string you can use for this already without needing string replacements. From here, it appears that the special characters are localised so there should be a way to create a DecimalFormat with a specific DecimalFormatSymbol based on the locale.

At least that's the case within Java proper. Whether Java Android can do the same thing, I'm not sure. They have been known to take a different tack on internationalisation before.


(a) Darn those Europeans and their funny numeric formats :-)

Upvotes: 2

Related Questions