LoginSignup
1
0

More than 1 year has passed since last update.

String.formatの使い方まとめ

Posted at

文字列を実装する中で文字列操作をする際にString.formatで実装する機会があったので備忘録。

String, Int, Doubleをそれぞれ使うように作成。
サンプルのユーザーデータは以下

data class User(
    // ニックネーム
    val nickname: String = "", 
    // 年齢
    val age: Int = 0,
    // 身長(cm)
    val height: Int = 0,
    // 足のサイズ(cm)
    val shoeSize: Double = 0.0,
)

実際の表示確認は以下


fun main(args: Array<String>) {   
    val jack = User(nickname = "ジャック", age = 27, height = 172, shoeSize= 26.5)

    print(String.format("ニックネーム:%s", jack.nickname))
    // ニックネーム:ジャック
    print(String.format("年齢:%d歳", jack.age))
    // 年齢:27歳
    print(String.format("身長:%dcm", jack.height))
    // 身長:172cm
    print(String.format("足のサイズ:%.1fcm", jack.shoeSize))
    // 足のサイズ:26.5cm
}

【メモ】
文字列Stringは「%s」
Int10進数は「%d」

少数が厄介で、「%.1f」と設定しているが、小数点第一位まで表示を定義している

12.34みたいな小数点第二位までなら「%.2f」になる。

【参考文献】
https://java-code.jp/173

1
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
1
0