Search code examples
javakotlinlocalenumber-formatting

How to get the Locale of a NumberFormat in Java/Kotlin?


According to https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html, NumberFormat.getInstance() will get you a NumberFormat instance in the current locale. I would like to verify after creating the instance what the locale is using a method like getLocale(), but no such method seems to be documented there.

The best I could do to ascertain this was to call Locale.getDefault() in the Kotlin shell (kotlinc):

>>> import java.math.BigDecimal
>>> import java.text.NumberFormat
>>> NumberFormat.getInstance().format(BigDecimal(1500))
1,500
>>> import java.util.Locale
>>> Locale.getDefault()
en_US

Is there no NumberFormat.getLocale() method?


Solution

  • Is there no NumberFormat.getLocale() method?

    There is not - what you can do, though is call the same method that NumberFormat.getInstance() does under the hood:

    Locale defaultLocale = Locale.getDefault(Locale.Category.FORMAT);
    

    There are two Category's in Java 8: https://docs.oracle.com/javase/8/docs/api/java/util/Locale.Category.html. If you need the DISPLAY one, just swap out the arg.