Parthiban M
Parthiban M

Reputation: 1104

android to add comma for the numbers which are in String

I'm getting a string from Json response as follows:

"Your account balance is 100000 as on Monday"

In this I need to add comma to the numerical value. Can anyone please help me how I can add this.Thanks in advance.

In this case, I would like to have the output in the following format:

"Your account balance is 100,000 as on Monday"

Upvotes: 0

Views: 151

Answers (2)

arsenikt
arsenikt

Reputation: 61

final String jsonString = "Your account balance is 100000 as on Monday";

DecimalFormat decFormat = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
decFormat.setGroupingUsed(true);
decFormat.setGroupingSize(3);

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(jsonString);
while (m.find()) {
    System.out.println(decFormat.format(Double.valueOf(m.group())));
}

Upvotes: 0

williamj949
williamj949

Reputation: 11316

NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
if (anotherFormat instanceof DecimalFormat) {
    DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
    anotherDFormat.applyPattern("#.00");
    anotherDFormat.setGroupingUsed(true);
    anotherDFormat.setGroupingSize(3);

    for (double d : numbers) {
        System.out.println(anotherDFormat.format(d));
    }
}

Upvotes: 3

Related Questions