Skip to content

Commit ea6a53b

Browse files
author
Nicolai Parlog
committed
Demonstrate CompactNumberFormat
1 parent 7acac38 commit ea6a53b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ Check out the [jpms](http://blog.codefx.org/tag/jpms/) tag on my blog, [this dem
8484

8585
## Updated APIs
8686

87+
*[formating numbers](src/main/java/org/codefx/demo/java12/api/format)
8788
*[`String`](src/main/java/org/codefx/demo/java11/api/string) ([article](https://blog.codefx.org/java/java-11-gems/))
8889
*[I/O](src/main/java/org/codefx/demo/java11/api/io) ([article](https://blog.codefx.org/java/java-11-gems/))
8990
*[`Predicate` / `Pattern`](src/main/java/org/codefx/demo/java11/api/predicate) ([article](https://blog.codefx.org/java/java-11-gems/))
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package org.codefx.demo.java12.api.format;
2+
3+
import java.text.NumberFormat;
4+
import java.text.NumberFormat.Style;
5+
import java.util.Locale;
6+
7+
public class CompactFormat {
8+
9+
public static void main(String[] args) {
10+
followers();
11+
decimalPowers();
12+
}
13+
14+
private static void followers() {
15+
NumberFormat followers = NumberFormat
16+
.getCompactNumberInstance(new Locale("en", "US"), Style.SHORT);
17+
followers.setMaximumFractionDigits(1);
18+
System.out.println(followers.format(5412) + " followers");
19+
}
20+
21+
private static void decimalPowers() {
22+
NumberFormat shortened = NumberFormat
23+
.getCompactNumberInstance(new Locale("en", "US"), Style.SHORT);
24+
NumberFormat shortenedWithFraction = NumberFormat
25+
.getCompactNumberInstance(new Locale("en", "US"), Style.SHORT);
26+
shortenedWithFraction.setMaximumFractionDigits(1);
27+
28+
for (int exp = 0; exp <= 12; exp++)
29+
for (int secondDigit : new int[]{ 4, 5 }) {
30+
double number = Math.pow(10, exp) + secondDigit * Math.pow(10, exp - 1);
31+
System.out.printf(
32+
"%,f ~> %s / %s%n",
33+
number,
34+
shortened.format(number),
35+
shortenedWithFraction.format(number));
36+
}
37+
}
38+
39+
}

0 commit comments

Comments
 (0)