0
0

More than 3 years have passed since last update.

小数点を起点に文字列を分割(index.Of , substring使用)

Posted at

背景

小数点の前と後で計算方法を変えたいときに少し躓き、解決したのでメモしておきます。

環境

Eclipse Neon 4.6.3
Java8

使用クラス

・文字列に小数点が含まれているかどうか
 int 変数名 = 文字列の変数.indexOf("調べたい文字");

・小数点の前後の文字列の取得
 文字列の変数.substring(x , y);
 x = 初めの文字の位置
 y = 終わりの文字の位置(省略可)

使ってみた

public class strPractice {

    public static void main(String[] args) {        

        String a = "12345.6789";

        //文字列に"."が含まれているか
        //含まれていればその場所(0から始まる)、なければ-1を返す
        int b = a.indexOf(".");
        System.out.println((b + 1) + "番目に含まれています。");

        //調べた文字を起点に分割
        //前半
        String c = a.substring(0 , b);
        System.out.println("小数点までの文字は" + c + "です。");

        //後半
        String d = a.substring(b + 1);
        System.out.println("小数点から後の文字は" + d + "です。");

    }

}

実行結果

6番目に含まれています。
小数点までの文字は12345です。
小数点から後の文字は6789です。

まとめ

formで受け取った小数を二進数に変換する場合にこの方法を使いました(二進数は小数点以下の計算が特殊なため)。普通は住所とかで使うのではないかと思いました。

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