-
-
Save sam43/0f06c84f3ce5ee00612e63a0f204af04 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