Hello guys, how to code in wasm in this case? is t...
# multiplatform
u
Hello guys, how to code in wasm in this case? is this correct or there are better ways? • common
Copy code
expect fun formatCurrency(amount: Double, currencySign: String): String
I just used AI but in IDE it's unreacheable
• jvm and android
Copy code
actual fun formatCurrency(amount: Double, currencySign: String): String {
  return "$currencySign${String.format(Locale.getDefault(), " %, .2f", amount)}"
}
• wasm ( i don't know how)
Copy code
wasm ( I don't know how to)
actual fun formatCurrency(amount: Double, currencySign: String): String {
    val jsFormattingFunction = js("""
        (function(amountToFormat, sign) {
            let locale;
            if (typeof navigator !== 'undefined' && navigator.language) {
                locale = navigator.language;
            } else {
                // Fallback for environments without navigator (e.g., Node.js for testing, though Intl exists)
                // Or if you want to force a specific locale as a default in non-browser.
                // For WasmJS typically targeting browsers, navigator.language is the way.
                locale = 'en-US'; // A sensible default
            }

            // Intl.NumberFormat handles grouping and fraction digits.
            const numberFormatter = new Intl.NumberFormat(locale, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
                useGrouping: true // Corresponds to the ',' in "%,.2f"
            });

            let formattedNumber = numberFormatter.format(amountToFormat);

            // Emulate the space prefix for positive numbers from " %,.2f"
            // String.format(" %,.2f", 123.45) -> " 123.45"
            // String.format(" %,.2f", -123.45) -> "-123.45"
            if (amountToFormat >= 0) {
                // Check if it already starts with a sign (e.g. some locales might add '+')
                // Though typically Intl.NumberFormat doesn't add '+' unless explicitly configured
                // and the " " flag in printf is specifically for positive numbers lacking a sign.
                if (formattedNumber.length > 0 && formattedNumber.charAt(0) !== '+' && formattedNumber.charAt(0) !== '-') {
                     formattedNumber = ' ' + formattedNumber;
                }
            }

            return sign + formattedNumber;
        })
    """) as (Double, String) -> String

    // Call the JavaScript function.
    // We need to cast the js(...) result to the correct function type.
    // The `as (Double, String) -> String` cast tells Kotlin the expected signature.
    return jsFormattingFunction(amount, currencySign)

}
l
You want to avoid storing currencies in floating-point variables, since they're not exact.