Last active
June 12, 2022 17:27
-
-
Save jongha/e7acfb24ef9cbfb0c4c41887b50b03bd to your computer and use it in GitHub Desktop.
Remove trailing zeros in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<resources> | |
<string name="int_format">%1$,d</string> | |
<string name="float_format">%1$,f</string> | |
</resources> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
value.orEmpty().trimEnd { it == '0' }.trimEnd { it == '.' }.trimEnd { it == ',' }