Skip to content
Go back

Local Rules: Localization and Locale-Aware Formatting in Compose Multiplatform

by KMP Bits

KMP Bits Cover

Every circuit on the calendar has a document the drivers rarely talk about: the local rules. Same championship, same car, same sporting regulations. Then you arrive at a track where the pit lane limit is lower, the flag marshals use a different start procedure, and the briefing is in a language half the paddock reads through a translator. Nothing about the car changed. Everything around it did.

An app shipped to more than one country lives the same weekend. The code is the car. The strings, the plurals, the way a price is written and the way a date reads are the local rules, and they change at every border.


The bug that wasn’t in my strings

I translated the first screen of an app into Portuguese and called it done. Every label was in the right language. Then I looked at the cart header and it said “1 items”. In Portuguese it said “0 item”, because my hand-rolled if (count <= 1) had decided zero was singular, and a few lines down the total read 1,234.50 in a country that writes 1.234,50.

The strings were translated. The app was not localized. Those are two different jobs, and I had only done the cheap one.

What I had assumed was that localization is a lookup table: key in, translated text out. It isn’t. Plurals are grammar, not text. Numbers and dates are formatting, not translation. And the last one is the one that bit me hardest on iOS: the platform already knows how to do all of this, and my shared code was quietly ignoring it.


Strings and plurals with Compose Resources

Compose Multiplatform ships its own resource system, and strings live in composeResources inside the module that owns them. Default language in values, other languages in a qualified folder:

composeApp/src/commonMain/composeResources/
├── values/strings.xml
├── values-pt/strings.xml
└── values-pt-rPT/strings.xml
<!-- values/strings.xml -->
<resources>
    <string name="checkout_title">Checkout</string>
    <plurals name="cart_items">
        <item quantity="one">%1$d item</item>
        <item quantity="other">%1$d items</item>
    </plurals>
</resources>
<!-- values-pt/strings.xml -->
<resources>
    <string name="checkout_title">Finalizar compra</string>
    <plurals name="cart_items">
        <item quantity="one">%1$d item</item>
        <item quantity="other">%1$d itens</item>
    </plurals>
</resources>

In a composable, you read them through the generated Res class:

// commonMain
@Composable
fun CartHeader(count: Int) {
    Text(
        text = pluralStringResource(Res.plurals.cart_items, count, count),
        style = MaterialTheme.typography.titleMedium,
    )
}

Note the count appears twice. The first one picks the plural form, the second one fills %1$d. I forgot the second one the first time and shipped a string with a literal %1$d in it for about ten minutes.

Outside a composable, in a ViewModel or a use case, the same lookup is a suspend function:

// commonMain
suspend fun buildReceiptTitle(): String = getString(Res.string.checkout_title)

Which tells you where to draw the line. If a string reaches the user, resolve it as late as possible, ideally in the UI. A ViewModel that calls getString has decided the language at the moment of the call, and it will not change if the user switches locale while the screen is alive. Expose a sealed type or a resource key and let the composable resolve it.


Plural rules are per language, not per app

English has two plural forms. Portuguese has more than the XML above admits to, and the rules differ between regions. In Brazilian Portuguese zero counts as one. In European Portuguese it falls into other. Compose Resources follows the CLDR rules and picks the rule from the device locale, region included, not from the folder the string came from. The same values-pt file prints “0 item” on a phone set to Brazil and “0 itens” on one set to Portugal, and both are right for their reader. A values-pt-rPT folder is for different words, not a different rule.

I will not pretend I have memorised the plural categories of every language. Arabic has six. Polish has several that depend on the last digits of the number. The practical rule is simpler: never build a plural with if (count == 1), never concatenate a number and a noun, and give your translators the quantity slots for their language instead of the two you happen to need in English.


Numbers, currency and dates are not in your resource files

Here is the part Compose Resources does not do for you. A string file can hold a pattern, but it cannot know that 1234.5 is 1,234.50 in one country and 1.234,50 in another, or that the same instant is 12/03/2026 or 3/12/2026 depending on who is looking.

kotlinx-datetime gives you correct instants and calendar maths. It deliberately does not format for a locale. For that, I go back to the platform with expect/actual:

// commonMain
expect class LocaleFormatter() {
    fun currency(amount: Double, currencyCode: String): String
    fun date(epochMillis: Long): String
}
// androidMain
actual class LocaleFormatter actual constructor() {

    actual fun currency(amount: Double, currencyCode: String): String =
        NumberFormat.getCurrencyInstance().apply {
            currency = Currency.getInstance(currencyCode)
        }.format(amount)

    actual fun date(epochMillis: Long): String =
        DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(epochMillis))
}
// iosMain
actual class LocaleFormatter actual constructor() {

    actual fun currency(amount: Double, currencyCode: String): String {
        val formatter = NSNumberFormatter().apply {
            numberStyle = NSNumberFormatterCurrencyStyle
            this.currencyCode = currencyCode
        }
        return formatter.stringFromNumber(NSNumber(double = amount)).orEmpty()
    }

    actual fun date(epochMillis: Long): String {
        val formatter = NSDateFormatter().apply {
            dateStyle = NSDateFormatterMediumStyle
            timeStyle = NSDateFormatterNoStyle
        }
        return formatter.stringFromDate(
            NSDate.dateWithTimeIntervalSince1970(epochMillis / 1000.0)
        )
    }
}

Both NumberFormat.getCurrencyInstance() and NSNumberFormatter read the device locale by default. That is the point. I do not pass a locale in, I do not keep a map of separators in commonMain, and I do not write a formatPrice function with a replace(".", ",") in it. I tried that on day one. It worked for exactly one country.

One thing to decide on purpose: the currency code is data, not locale. A user in Portugal can look at a price in dollars. The locale decides how the number is written, the currency code decides what it is. Keep them as separate inputs.


Letting the user pick a language inside the app

By default the app follows the device. That is the right default and most apps should stop there. When a product requirement says the user must be able to override the language in settings, you are outside what the resource system does on its own. Compose Multiplatform still has no public API for this. The official docs describe an expect/actual LocalAppLocale and call it a temporary workaround until a common API exists.

What I have seen work is a small wrapper that provides an overriding locale to the tree and forces recomposition when it changes. It is a few lines on Android and a few more on iOS, and the two do not behave the same around the formatter above. On Android the documented approach calls Locale.setDefault, so NumberFormat follows along. On iOS it writes AppleLanguages to the user defaults, and NSNumberFormatter keeps reading the system locale. If you override the language in the UI, pass the same override to the formatter, or the iOS screen will say “Finalizar compra” next to a price written the English way.

That mismatch is the failure I find hardest to catch in review, because every individual piece is correct.


Gotchas I have already paid for

Text length is a layout bug waiting to happen. German and Portuguese run longer than English, often by a third. A button that fits “Pay now” will clip “Jetzt bezahlen”. Test with the longest language, not the one you develop in.

Never build a sentence from fragments. "You have " + count + " " + noun cannot be translated, because word order changes between languages. Use one string with placeholders and let the translator move them.

Missing translations fall back silently. A key present in values and absent in values-pt will show English to a Portuguese user without any error. I diff the key sets of each folder in CI. A short script is enough.

Dates need a time zone decision. Formatting an instant uses the device zone. A flight departure should be formatted in the airport’s zone, not the phone’s. That is a separate input to the formatter, same as the currency code.

Previews and tests use the default locale. Your UI tests pass in English and prove nothing about Portuguese. Run at least one pass with a non-default locale, especially for plurals.


Wrapping up

Localization is two jobs that happen to share a folder name. Strings and plurals belong to Compose Resources, resolved late and in the UI. Numbers, currencies and dates belong to the platform, and the shared code should ask for them, not reimplement them.

If your commonMain contains a hand-written thousands separator, it has already lost. Hand the formatting to the system that knows the locale, and keep the car identical everywhere.

Same car at every circuit, local rules read before the lights go out. 🏁


The KMP Bits app is available on App Store and Google Play — built entirely with KMP.


Share this post on:

Comments

0 / 250

Loading comments...


Next Post
Radio Check, No Answer: The Hidden Cost of Handing Everything to AI