https://kotlinlang.org logo
#webassembly
Title
# webassembly
j

John O'Reilly

02/25/2024, 10:10 PM
What would be the equivalent of
java.text.NumberFormat
when using Wasm based Compose for Web?
e

eygraber

02/25/2024, 10:28 PM
I'm doing this to replace
java.text.DecimalFormat
. There's probably some API that could do something similar for
java.text.NumberFormat
👍 1
j

jw

02/25/2024, 11:30 PM
Call out to Intl, presumably
j

John O'Reilly

02/26/2024, 11:59 AM
Call out to Intl, presumably
do you mean through something like
import js.intl.NumberFormat
? That works in Kotlin/JS but not wasm I think
j

jw

02/26/2024, 12:12 PM
That why I said "call out", as in, call into the JS runtime's JS API for Intl
j

jw

02/26/2024, 12:22 PM
Yeah. Define whatever subset of the API you need and you should be good.
👍 1
j

John O'Reilly

02/26/2024, 12:30 PM
Works great, thanks
Copy code
private external object Intl {
    class NumberFormat(locales: String, options: JsAny) {
        fun format(l: Double): String
    }
}

private fun formatPercentageOptions(): JsAny = js("({ style: 'percent', maximumFractionDigits: 2 })")
private fun formatAsUSDOptions(): JsAny = js("({ style: 'currency', currency: 'USD',})")

internal actual fun Double.formatPercentage(): String {
    val format = Intl.NumberFormat(
        locales = "en-US",
        options = formatPercentageOptions(),
    )
    return format.format(this)
}

internal actual fun Double.formatDollarAmount(): String {
    val format = Intl.NumberFormat(
        locales = "en-US",
        options = formatAsUSDOptions(),
    )
    return format.format(this)
}
6 Views