Skip to content

Commit b820c86

Browse files
Dominik AngererJoelQ
Dominik Angerer
authored andcommitted
TIL Formatting numbers by locale in Java
Added Number Formatting because that bugs a lot people and can be really useful to know & learn.
1 parent 6430cb5 commit b820c86

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

java/number-formatting.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# NumberFormatting
2+
3+
## Assignment
4+
Format a number for a specific locale. For example, the number 12345.123 should be formatted as `12,345.12` in the USA locale, but `12.345,12` in the German locale.
5+
6+
## Solution
7+
```java
8+
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
9+
10+
currencyFormatter.setMaximumFractionDigits(2);
11+
currencyFormatter.setMinimumFractionDigits(2);
12+
13+
System.out.println(currencyFormatter.format(12345.12));
14+
```
15+
16+
Depending on your default Locale the currencyFormatter will format the number the right way.
17+
18+
##### If you have a locale like `Locale.US` it will output:
19+
```java
20+
12,345.12
21+
```
22+
23+
##### Or if you have a locale like `Locale.GERMANY`:
24+
```java
25+
12.345,12
26+
```
27+
28+
### What about the Locale
29+
Using `Locale.getDefault()` allows you to get the System default, so it depends on your settings. You can test it for other Locale's by using fixed locale values like: `Locale.GERMAN`or `Locale.US` for USA. You also can find the Local according to the `language`/`country` by using `Locale(String language)` or `Locale(String language, String country)`. More details can be found here: [Documentation for Locale].
30+
31+
### Executable Online Java Example:
32+
Here is an in-browser example that you can try: [Coding Ground Example]
33+
Steps to run: compile and execute.
34+
35+
[Coding Ground Example]:http://www.tutorialspoint.com/compile_java_online.php?PID=0Bw_CjBb95KQMbHZ0NWc1OVRONkE
36+
[Documentation for Locale]:http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html

0 commit comments

Comments
 (0)