Hello , how to write this function is best way ? `...
# codereview
k
Hello , how to write this function is best way ?
Copy code
fun String?.trimTrailingZeros(): String? {
    if (isNullOrEmpty() || this!!.indexOf(".") < 0) return this
    return replace("0*$".toRegex(), "").replace("\\.$".toRegex(), "")
}
e
IMO it would be better to define it on
String
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-nullable
3
anyway, given that,
Copy code
fun String.trimTrailingZeros(): String =
    if ('.' in this) trimEnd('0').trimEnd('.') else this
would be a straightforward translation without using regex
👍 3
k
Ahh nice thanks 🙂
m
@ephemient very cool solution but I suspect it won’t always work. For example, this is what the OP wanted and it works:
Copy code
"1.000".trimTrailingZeros() --> 1
but these cases don’t work as expected:
Copy code
"1.1000".trimTrailingZeros() --> 1.1
"1.10200".trimTrailingZeros() --> 1.102
is this correct?
👆 1
e
that's what the original function returns too
m
Oh I see maybe I got it wrong sorry…
e
why wouldn't it be correct?
m
never mind, I misunderstood the requirement when reading the code 😄
m
Or just
replace("[.]?0*$".toRegex(), "")
(although still need to check a period exists before calling this).
Note: the
trimEnd()
function will remove all trailing characters and so is a little different from the OP’s second regex which only replaces last period.
e
if there are multiple
.
in a row, yeah. that's actually easy to resolve if it is an issue though,
Copy code
trimEnd('0').removeSuffix(".")
b
if they are numbers you could do a .toDouble().toString() as in: https://pl.kotl.in/An1Dc6M3Q
of course it has to fit in Double etc etc