We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. We call replace with /,/g to match all commas and replace them all with empty strings.
In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left. After writing the above code (python format number with commas), Ones you will print “numbers” then the output will appear as a “ 5,000,000”.
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646
You ask for quickest, but perhaps you mean "best" or "correct" or "typical"?
You also ask for commas to indicate thousands, but perhaps you mean "in normal human readable form according to the local custom of your user"?
You do it as so:
int i = 35634646;
String s = NumberFormat.getIntegerInstance().format(i);
Americans will get "35,634,646"
Germans will get "35.634.646"
Swiss Germans will get "35'634'646"
int bigNumber = 1234567;
String formattedNumber = String.format("%,d", bigNumber);
Integers:
int value = 100000;
String.format("%,d", value); // outputs 100,000
Doubles:
double value = 21403.3144d;
String.format("%,.2f", value); // outputs 21,403.31
String.format is pretty powerful.
- Edited per psuzzi feedback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With