kotlin currency format

import java.text.NumberFormat
import java.util.Currency
import java.util.Locale

fun formatCurrency(amount: Double, currencyCode: String): String {
    val locale = Locale.getDefault()
    val currency = Currency.getInstance(currencyCode)
    val formatter = NumberFormat.getCurrencyInstance(locale)

    formatter.currency = currency
    return formatter.format(amount)
}

fun main() {
    val amount = 1234.56
    val currencyCode = "USD"
    val formattedAmount = formatCurrency(amount, currencyCode)
    println("Formatted Amount: $formattedAmount")
}

This Kotlin code snippet demonstrates how to format a currency using the NumberFormat class from java.text. The formatCurrency function takes a Double amount and a currency code as input parameters. Inside the function: - Locale.getDefault() retrieves the default locale. - Currency.getInstance(currencyCode) creates a Currency instance based on the provided currency code. - NumberFormat.getCurrencyInstance(locale) creates a NumberFormat instance for formatting currency in the specified locale. - formatter.currency = currency sets the currency for the formatter. - formatter.format(amount) formats the amount using the specified currency and returns the formatted string.

In the main function: - amount and currencyCode variables are initialized with sample values. - formatCurrency function is called with the amount and currencyCode. - The formatted amount is printed to the console using println.