KV
09/21/2020, 4:56 AMfun String?.trimTrailingZeros(): String? {
if (isNullOrEmpty() || this!!.indexOf(".") < 0) return this
return replace("0*$".toRegex(), "").replace("\\.$".toRegex(), "")
}ephemient
09/21/2020, 5:32 AMString instead of String?. it returns null iff the receiver is null, so instead of doing that, just push the safe call to the consumers, e.g. nullable?.trimTrailingZeros(). if the receiver is non-nullable, this will ensure the result is also non-nullableephemient
09/21/2020, 5:33 AMfun String.trimTrailingZeros(): String =
if ('.' in this) trimEnd('0').trimEnd('.') else this
would be a straightforward translation without using regexKV
09/21/2020, 5:33 AMMatteo Mirk
09/21/2020, 1:10 PM"1.000".trimTrailingZeros() --> 1
but these cases don’t work as expected:
"1.1000".trimTrailingZeros() --> 1.1
"1.10200".trimTrailingZeros() --> 1.102
is this correct?ephemient
09/21/2020, 1:11 PMMatteo Mirk
09/21/2020, 1:11 PMephemient
09/21/2020, 1:11 PMMatteo Mirk
09/21/2020, 1:12 PMMark
09/22/2020, 10:32 AMreplace("[.]?0*$".toRegex(), "") (although still need to check a period exists before calling this).Mark
09/22/2020, 10:34 AMtrimEnd() function will remove all trailing characters and so is a little different from the OP’s second regex which only replaces last period.ephemient
09/22/2020, 5:06 PM. in a row, yeah. that's actually easy to resolve if it is an issue though,
trimEnd('0').removeSuffix(".")bjonnh
09/23/2020, 8:46 PMbjonnh
09/23/2020, 8:46 PM