Search code examples
kotlinformattingcurrency

Force currency formatting in [Kotlin]


I found a formatting variation of the currency depending of your locale string value. I mean, I understand it depends of the local keyboard language. My question is if it's possible to force a currency format not depending of the local keyboard language. Here's an example

https://gist.github.com/ccampo133/e6315a4d2678be394ff62c7897bfaa48

  Locale("es", "ES"), // Spanish - Spain
            Locale("en", "ES"), // English - Spain
            Locale("es", "MX"), // Spanish - Mexico
            Locale("en", "MX"), // English - Mexico

/*
 * OUTPUT:
 *
 * Currency: MXN
 * Locale: es_ES     Formatted value: 1.234,56 MXN
 * Locale: en_ES     Formatted value: MXN1,234.56
 * Locale: es_MX     Formatted value: $1,234.56
 * Locale: en_MX     Formatted value: MXN1,234.56
*/


   val format: NumberFormat = NumberFormat.getCurrencyInstance()
    format.maximumFractionDigits = 2
    format.currency = Currency.getInstance("MXN")

for example I want to always get the en_ES format I don't know if it's possible to make

Thank you so much


Solution

  • Pass the desired Locale to getCurrencyInstance():

    val format = NumberFormat.getCurrencyInstance(Locale("es", "MX"))