자바 정수, 실수 변환 - jaba jeongsu, silsu byeonhwan

java 에서

특정 문자열을

정수 혹은 실수로 변환해야 하는 경우가 많습니다.

그중에서

실수로 변환해야 하는 경우에는 아래와 같은 방법으로 하시면 됩니다.

우선 아래와 같은 문자열이 있다고 가정하고,

String str = "1.1";

실수로 변환하려면 아래처럼 

Float class 의 valueOf 를 이용하시면 됩니다.

float num = Float.valueOf(str)

그러면 결과는 실수로 1.1 이 나오게 됩니다!

참고들 하세요!

Math 라이브러리의 round()를 이용하여 float을 int로 변환할 수 있습니다. round()는 실수를 반올림하여 정수로 변환합니다. 결과를 보시면 반올림하여 변환하는 것을 알 수 있습니다.

public class ConvertFloatToInt2 {

    public static void main(String[] args) {

        float f1 = 1.45f;
        int n1 = Math.round(f1);

        float f2 = 1.95f;
        int n2 = Math.round(f2);

        float f3 = -1.45f;
        int n3 = Math.round(f3);

        float f4 = -1.95f;
        int n4 = Math.round(f4);

        System.out.println("n1: " + n1);
        System.out.println("n2: " + n2);
        System.out.println("n3: " + n3);
        System.out.println("n4: " + n4);
    }
}

Output:

n1: 1
n2: 2
n3: -1
n4: -2

3. Math : ceil()

Math 라이브러리의

n1: 1
n2: 1
n3: -1
n4: -1
1를 이용하여 float을 int로 변환할 수 있습니다.
n1: 1
n2: 1
n3: -1
n4: -1
1는 실수를 올림하여 정수로 변환합니다. 결과를 보시면 올림하여 변환되는 것을 알 수 있습니다.

public class ConvertFloatToInt3 {

    public static void main(String[] args) {

        float f1 = 1.45f;
        int n1 = (int) Math.ceil(f1);

        float f2 = 1.95f;
        int n2 = (int) Math.ceil(f2);

        float f3 = -1.45f;
        int n3 = (int) Math.ceil(f3);

        float f4 = -1.95f;
        int n4 = (int) Math.ceil(f4);

        System.out.println("n1: " + n1);
        System.out.println("n2: " + n2);
        System.out.println("n3: " + n3);
        System.out.println("n4: " + n4);
    }
}

Output:

n1: 2
n2: 2
n3: -1
n4: -1

4. Math : floor()

Math 라이브러리의

n1: 1
n2: 1
n3: -1
n4: -1
3를 이용하여 float을 int로 변환할 수 있습니다.
n1: 1
n2: 1
n3: -1
n4: -1
3는 실수를 버림하여 정수로 변환합니다. 결과를 보시면 버림하여 변환되는 것을 알 수 있습니다.