Skip to content

Instantly share code, notes, and snippets.

@gosr
Last active November 4, 2022 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosr/5dca7ac82c85acd617a2e8660e6a7080 to your computer and use it in GitHub Desktop.
Save gosr/5dca7ac82c85acd617a2e8660e6a7080 to your computer and use it in GitHub Desktop.
Int.zeroPrefixed
/**
* Kotlin stdlib doesn't have a 'String.format()' that's not relying on JVM.
* https://youtrack.jetbrains.com/issue/KT-25506/Stdlib-Stringformat-in-common
*
* To keep things in common code, this "formatter" simply prefixes an Int string with zeros
* if needed.
* For example, 1.zeroPrefixed(2) returns "01".
*/
fun Int.zeroPrefixed(
maxLength: Int,
): String {
if (this < 0 || maxLength < 1) return ""
val string = this.toString()
val currentStringLength = string.length
return if (maxLength <= currentStringLength) {
string
} else {
val diff = maxLength - currentStringLength
var prefixedZeros = ""
repeat(diff) {
prefixedZeros += "0"
}
"$prefixedZeros$string"
}
}
import kotlin.test.Test
import kotlin.test.assertEquals
class ZeroPrefixedTests {
@Test
fun `format 1 to 01`() {
val actual = 1.zeroPrefixed(maxLength = 2)
val expected = "01"
assertEquals(expected, actual)
}
@Test
fun `format 2 to 02`() {
val actual = 2.zeroPrefixed(maxLength = 2)
val expected = "02"
assertEquals(expected, actual)
}
@Test
fun `format 10 to 10`() {
val actual = 10.zeroPrefixed(maxLength = 2)
val expected = "10"
assertEquals(expected, actual)
}
@Test
fun `format 10 to 010`() {
val actual = 10.zeroPrefixed(maxLength = 3)
val expected = "010"
assertEquals(expected, actual)
}
@Test
fun `format 2 to 002`() {
val actual = 2.zeroPrefixed(maxLength = 3)
val expected = "002"
assertEquals(expected, actual)
}
@Test
fun `format 2 to 00002`() {
val actual = 2.zeroPrefixed(maxLength = 5)
val expected = "00002"
assertEquals(expected, actual)
}
@Test
fun `format 12 to 00012`() {
val actual = 12.zeroPrefixed(maxLength = 5)
val expected = "00012"
assertEquals(expected, actual)
}
@Test
fun `format 12345 to 12345`() {
val actual = 12345.zeroPrefixed(maxLength = 5)
val expected = "12345"
assertEquals(expected, actual)
}
@Test
fun `format negative int to empty string`() {
val actual = (-1).zeroPrefixed(maxLength = 5)
val expected = ""
assertEquals(expected, actual)
}
@Test
fun `format to empty string if maxLength is below 1`() {
val actual = 123.zeroPrefixed(maxLength = 0)
val expected = ""
assertEquals(expected, actual)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment