Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to Insert Commas into Large Numbers

Is there a method that already exists and if not can a method be written that can format large numbers and insert commas into them?

100     = 100
1000    = 1,000  
10000   = 10,000
100000  = 100,000
1000000 = 1,000,000


public String insertCommas(Integer largeNumber) {

}
like image 264
ThreaT Avatar asked Feb 13 '14 10:02

ThreaT


People also ask

How do I put commas in numbers in Excel?

To enable the comma in any cell, select Format Cells from the right-click menu and, from the Number section, check the box of Use 1000 separator (,). We can also use the Home menu ribbons' Commas Style under the number section.

Why do we use commas in large numbers?

In English, you can use commas in numbers of four digits or longer (i.e., numbers above 999) after every third digit from the right. These “thousands separators” make it easier to read long numbers since we can see where the different groups of digits fall at a glance.

How do I automatically insert commas between numbers in Word?

In the Add Text dialog, type comma , into Text textbox, check After last character option. 3. Click Apply or Ok to add comma into each cell.


2 Answers

With NumberFormat you can do this easily:

NumberFormat format = NumberFormat.getInstance(Locale.US);

System.out.println(format.format(100));
System.out.println(format.format(1000));
System.out.println(format.format(1000000));

will ouput:

100
1,000
1,000,000
like image 186
Weibo Li Avatar answered Sep 28 '22 00:09

Weibo Li


You can use NumberFormat#getNumberInstance with Locale.US:

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation— the number should be formatted according to the customs and conventions of the user's native country, region, or culture.


System.out.println(NumberFormat.getNumberInstance(Locale.US).format(10000000));

This will print:

10,000,000

Side note: In Java 7, you can write an int with underscores: 1_000_000.

like image 27
Maroun Avatar answered Sep 28 '22 00:09

Maroun