Ume Channel
05/19/2025, 6:12 PMexpect fun formatCurrency(amount: Double, currencySign: String): String
Ume Channel
05/19/2025, 6:15 PMUme Channel
05/19/2025, 6:30 PMactual fun formatCurrency(amount: Double, currencySign: String): String {
return "$currencySign${String.format(Locale.getDefault(), " %, .2f", amount)}"
}
Ume Channel
05/19/2025, 6:30 PMwasm ( 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)
}
loke
05/20/2025, 4:21 PM