kel
kel

Reputation: 29

Adding char in a specific string location

Hello I'm just a beginner in java and i have a problem adding a comma on a string of digits like for example 1000 will be 1,000 in output .

i can use :

String digitsWithComma = ""; digitsWithComma = str.substring(0,1) + "," + str.substring(1);

but the problem is it only works on a thousand not on a higher digits. can someone please help me with this

Upvotes: 0

Views: 42

Answers (1)

Jordan
Jordan

Reputation: 32522

Java has a concept called Number Formatting that seems to be what you're doing:

import java.text.NumberFormat;
String output = NumberFormat.getNumberInstance(Locale.US).format(1000000);

Since we gave it the US locale, it would print out 1,000,000.

Generally speaking, if you find yourself wondering "how can I implement X feature?" chances are good that Java already has a standard or built-in way of doing it, especially if you're dealing with formatting of any kind.

Upvotes: 2

Related Questions