Create a gist now

Instantly share code, notes, and snippets.

LocalesFormat Iterates over all locale available on current system and prints locale that use special characters to present digits. It also counts how many locales use dot and comma as a decimal delimiter. FormatterExercise compares performance of String.format() vs direct usage of Formatter class.
import java.util.Formatter;
public class FormatterExercise {
private static int n = 1_000_000;
public static void main(String[] args) throws InterruptedException {
long before = System.nanoTime();
str();
long after = System.nanoTime();
System.out.println((after - before)/1_000_000);
before = System.nanoTime();
fmt();
after = System.nanoTime();
System.out.println((after - before)/1_000_000);
}
public static CharSequence str() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < n; i++) {
buf.append(String.format("%d\n", 1));
}
return buf;
}
public static CharSequence fmt() {
StringBuilder buf = new StringBuilder();
Formatter fmt = new Formatter(buf);
for (int i = 0; i < n; i++) {
fmt.format("%d\n", 1);
}
return buf;
}
}
import java.util.Locale;
public class LocalesFormat {
public static void main(String[] args) {
int decimalDot = 0;
int decimalComma = 0;
for (Locale locale : Locale.getAvailableLocales()) {
String one = String.format(locale, "%d", 1);
if (!"1".equals(one)) {
System.out.println("\t" +locale + ": " + one);
}
String pi = String.format(locale, "%.2f", 3.14);
if (pi.contains(".")) {
decimalDot++;
} else if(pi.contains(",")) {
decimalComma++;
} else {
System.out.println("\t" +locale + ": " + pi);
}
}
System.out.println(String.format("Total locales: %d\nDecimal dot: %d\nDecimal comma: %d", Locale.getAvailableLocales().length, decimalDot, decimalComma));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment