0

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

4
  • You could use regex replace, but for better understatement, try iterating over the string and using a similar method to yours ;) Commented Apr 6, 2017 at 16:31
  • 3
    What's your intent? format a number? Commented Apr 6, 2017 at 16:32
  • 2
    Also, you might use this: stackoverflow.com/questions/5323502/… Commented Apr 6, 2017 at 16:32
  • Seems a duplicate question, anyways, stackoverflow.com/questions/5379231/… Commented Apr 6, 2017 at 16:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.