Skip to content

Instantly share code, notes, and snippets.

@jongha
Last active June 12, 2022 17:27
Show Gist options
  • Save jongha/e7acfb24ef9cbfb0c4c41887b50b03bd to your computer and use it in GitHub Desktop.
Save jongha/e7acfb24ef9cbfb0c4c41887b50b03bd 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
}
}
}
@catsoft
Copy link

catsoft commented Jan 25, 2022

value.orEmpty().trimEnd { it == '0' }.trimEnd { it == '.' }.trimEnd { it == ',' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment