Video in progress

Senior ☕ Core Java

On the prod server, "TITLE".toLowerCase() or String.format("%.2f", x) gave a different result than on my local machine. What locale-related traps are there?

// the server OS locale is tr_TR, or -Duser.language=tr
String key = "TITLE".toLowerCase();          // "tıtle": not a plain 'i'
key.equals("title");                          // false

// the server is ru_RU
String amount = String.format("%.2f", 1.5);  // "1,50"
new BigDecimal(amount);                       // NumberFormatException

toLowerCase(), toUpperCase(), String.format and NumberFormat called without a locale take the JVM's default locale. In the Turkish locale, I becomes a dotless ı in lowercase, and in the Russian locale the decimal separator is a comma. For machine-readable text, always pass Locale.ROOT.

📖 Answer

Both lines work correctly from Java's point of view. The bug isn't in the code, it's in the assumption that "everyone has the same locale as me".

Locale.getDefault() is taken when the JVM starts, from the OS (LANG, Windows regional settings) or from -Duser.language/-Duser.country. That means the same JAR can behave three different ways on a developer's laptop, in CI and on a customer's Windows server.

Where it usually bites:

  • normalizing enum or header names: Status.valueOf(s.toUpperCase()) turns "paid" into "PAİD" in the Turkish locale and throws IllegalArgumentException;
  • writing numbers into SQL, JSON, CSV or logs: String.format and DecimalFormat put in a comma, and the next system can't read it;
  • Scanner.nextDouble() can also reject 1.5 depending on the locale;
  • dates: DateTimeFormatter.ofPattern("dd MMM") prints the month name in the default locale.

The rule is simple: if the text is for a machine, use Locale.ROOT; if it's for a person, use the user's explicit locale (the Accept-Language from the request), but never the server's default.

String key = raw.toLowerCase(Locale.ROOT);
String amount = String.format(Locale.ROOT, "%.2f", value);
// for money, don't format at all: value.toPlainString()

Systematic protection: Error Prone's StringCaseLocaleUsage check or the forbidden-apis plugin catches calls without a locale at build time. Setting the locale explicitly in the container image also helps, but it's only extra insurance: the code still has to state the locale itself. Try running the tests once with -Duser.language=tr: a lot of hidden spots show up right away.