Math.round() 사용(반올림)

public class practice {
    public static void main(String[] args) {
        double pi = 3.141592;

        System.out.println(pi); // 3.141592
        System.out.println(pi * 1000); // 3141.592
        System.out.println(Math.round(pi * 1000)); // 3142

        System.out.println(Math.round(pi * 1000) / 1000); // 3
        System.out.println((double)Math.round(pi * 1000) / 1000); // 3.142
        System.out.println(Math.round(pi * 1000) / 1000.0); // 3.142
    }
}

 
int 사용(버림)

public class practice {
    public static void main(String[] args) {
        double pi = 3.141592;

        System.out.println(pi*1000); // 3141.592

        System.out.println((int)pi*1000); // 3000
        System.out.println((int)(pi*1000)); // 3141

        System.out.println((int)(pi*1000)/1000); // 3
        System.out.println((int)(pi*1000)/1000.0); // 3.141
    }
}

 

반응형

'이것이 자바다 > JAVA1' 카테고리의 다른 글

비교 연산자 < > <= >= == !=  (0) 2023.05.16
나머지 연산자 %  (0) 2023.05.16
산술 변환  (0) 2023.05.15
형변환(casting)  (0) 2023.05.15
증감 연산자 전위형(prefix), 후위형(postfix)  (0) 2023.05.15

+ Recent posts