Padding to number at the begging using kotlin code

Padding to number at the begging using Koltin code 


Sometimes we need to show number with leading zero of integer like Entry Number: 000005
So we need padding for that integer.
In Kotlin we do it various way: -

 The padStart() function in Kotlin is a string extension function that pads the beginning of a string with a specified character or sequence of characters until the desired length is reached.

 
The padStart() function takes two parameters:
 
length: The desired length of the resulting string after padding, it is Int type parameter.
padChar: The character used for padding.
padStart(5, '0') here 5 is length of resulting string and ‘0’ is padded when create result string.
 
Example:
 val yourString = "hello"

val paddedResultString = yourString.padStart(10, '*')
println(paddedResultString)
// Output String : "*****hello"
 
For Integer Variable:
fun padBegining(intData:Int):String{
   
return intData.toString().padStart(10,'0')
}
// output : 0000000010 if we pass 10 to function padBegining(10)
For padding at end we have function pad End. Below is the example. .
fun padEndToString(strData:String):String{

    return strData.padEnd(10,'*')
}
 // output will be hello****** 
//when we pass padEndToString('hello')
 
2> format() function %d useful for padding integer value at beginning 
 
 fun padStringAtBeginingUsingformat(){

    val urIntVal = 42
   
val formattedString = "%10d".format(urIntVal)
   
println(formattedString)
// Output: "0000000042"
}

Comments

Popular posts from this blog

Adding Multilingual Support in Kotlin Android Apps

Create XL sheet using kotlin and poi in android

The Dhari Devi Temple