0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinで小数末尾の0を取り除く

Posted at

正規表現(Regex)を使って実装してみる

ケース1

22.0000のような数値文字列を22にする

fun main() {
    val str = "22.0000"

    val regex = Regex(".0+\$")

    val result = regex.replace(str, "") // 22
}

正規表現 .0+$ を使って .000000 部分にマッチさせて空文字にリプレースしてる。
Kotlinの文字列にするときは .0+\$ のように$をエスケープさせなくちゃいけないことに注意

あと、ついやりがちだけど、 """.0+$""" もダメ。今度は . が小数点じゃなくて正規表現の意味にとられるから。

ケース2

22.22200のような数値文字列を22.222にする

fun main() {
    val str = "22.0000"

    val regex = Regex("""0+$""")

    val result = regex.replace(str, "") // 22
}

今度は 0+$ を使ってやればおk

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?