Home > database >  Android In dutch language comma (,) is interpreted as dot (.)
Android In dutch language comma (,) is interpreted as dot (.)

Time:05-23

I am using the following code to format the amount entered by user in EditText.

fun String.formatWithComma(): String {
    return try {
        val formatter = DecimalFormat("#,###,###")
        formatter.format(toDouble())
    } catch (ex: Exception) {
        return ""
    }
}

But when I switch the phone language to dutch, the comma is converted to dot (.). Like if user wants to type 4,323 , it is converted to 4.323.

I want to comma instead of dot even in dutch language. Any solution

CodePudding user response:

Some European countries use comma and dot in the different way than USA and England. You should add an extra line to instruct it before you use it:

formatter.decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.ENGLISH)

CodePudding user response:

I am not sure, if this will fix your problem.

println("${"4.323.001".formatWithComma()}")

If we found multiple dots in the string, I am replacing that values, Improve this solution based on your needs.

fun String.formatWithComma(): String {
    return try {
        var lastIndexOf = this.lastIndexOf(".");
        var temp = this
        var temp2 = ""
        if(this.split(".").size >= 2)
        {
        temp = this.substring(0,lastIndexOf).replace(".","");
        temp2 = this.substring(lastIndexOf,this.length);    
        }
        
        val formatter = DecimalFormat("#,###,###.###")
        return formatter.format((temp temp2).toDouble())
    } catch (ex: Exception) {
        return ""
    }
}

CodePudding user response:

On the basis of answer given by AIMIN PAN

Final solution to fix this issue is

fun String.formatWithComma(): String {
    return try {
        val formatter = DecimalFormat("#,###,###")
        formatter.decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.ENGLISH)
        formatter.format(toDouble())
    } catch (ex: Exception) {
        return ""
    }
}
  • Related