Skip to content

Instantly share code, notes, and snippets.

@sam43
Forked from jongha/StringUtils.kt
Created June 12, 2022 17:27
Show Gist options
  • Save sam43/0f06c84f3ce5ee00612e63a0f204af04 to your computer and use it in GitHub Desktop.
Save sam43/0f06c84f3ce5ee00612e63a0f204af04 to your computer and use it in GitHub Desktop.
Remove trailing zeros in Kotlin
<resources>
<string name="int_format">%1$,d</string>
<string name="float_format">%1$,f</string>
</resources>
object StringUtils {
fun format(context: Context?, value: Float?): String? {
return trimZero(context?.resources?.getString(R.string.float_format, value ?: 0f))
}
fun format(context: Context?, value: Int?): String? {
return trimZero(context?.resources?.getString(R.string.int_format, value ?: 0))
}
fun trimTrailingZero(value: String?): String? {
return if (!value.isNullOrEmpty()) {
if (value!!.indexOf(".") < 0) {
value
} else {
value.replace("0*$".toRegex(), "").replace("\\.$".toRegex(), "")
}
} else {
value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment