Home > Blockchain >  Format number based on pattern
Format number based on pattern

Time:02-02

  • I need to format numbers based on pattern given in the code.
  • Number : 12038902.9, Pattern : "##,###,###.##". Output must be like : 12,038,902.9 I have to use this "##,###,###.##" & "##.###.###,##" also.

I have tried this but not working :

fun main() {
        val number = 12038902.90
        val pattern = "##,###,###.##"
        val formattedNumber = formatNumber(number, pattern)
        println(formattedNumber)
    }
    
    fun formatNumber(number: Double, pattern: String): String {
         val parts = pattern.split(".")
        val integerPart = parts[0].replace(",", "")
        val decimalPartFormat = parts[1]
    
        val intPartFormat = "%d"
        val decimalPartForm = "%.${decimalPartFormat.length}f"
    
        val formattedIntPart = String.format(intPartFormat, number.toInt()).replaceFirst("(?<=\\d)(?=(\\d{3}) (?!\\d))".toRegex(), ",")
        val decimalPart = (number * 10.0.pow(decimalPartFormat.length)).toInt() % 10.0.pow(decimalPartFormat.length).toInt()
        val formattedDecimalPart = String.format("%0${decimalPartFormat.length}d", decimalPart).replaceFirst("0*$".toRegex(), "").replaceFirst("(?<=\\d)(?=(\\d{3}) (?!\\d))".toRegex(), ",")
    
        return "$formattedIntPart.$formattedDecimalPart"
    }

Getting this output : 12,038902.9 which is wrong I want is 12,038,902.9:

Pattern & number both are dynamic so I need to adjust as per it's need.

CodePudding user response:

maybe u can use DecimalFormat for this purpose. It takes care of grouping, proper separators etc. Result for your the input 12038902.9 is: 12,038,902.9

fun convert(number: String) {
    val decimalFormatSymbols = DecimalFormatSymbols()
    decimalFormatSymbols.decimalSeparator = '.'
    decimalFormatSymbols.groupingSeparator = ','

    val decimalFormat = DecimalFormat()
    decimalFormat.decimalFormatSymbols = decimalFormatSymbols
    decimalFormat.groupingSize = 3

    decimalFormat.maximumFractionDigits = 2
    decimalFormat.minimumFractionDigits = 1

    decimalFormat.maximumIntegerDigits = 8
    decimalFormat.maximumIntegerDigits = 8

    val formattedNumber = decimalFormat.format(number.toDoube())

    println(formattedNumber)
}

CodePudding user response:

Try with:

val number = 12038902.9
val pattern = "##,###,###.##"

val formattedNumber = DecimalFormat(pattern).format(number)
  • Related