SeouliteLab

[Java/자바] float을 int로 변환하는 방법 본문

프로그래밍

[Java/자바] float을 int로 변환하는 방법

Seoulite Lab 2024. 3. 9. 01:01

float을 int로 변환하는 방법에는 몇 가지 방법이 있습니다. 이 글에서는 여러 가지 방법을 예제와 함께 설명하겠습니다.

1. 형변환 연산자 사용

가장 간단한 방법은 형변환 연산자를 사용하는 것입니다. 하지만 이 방법은 데이터 손실이 발생할 수 있습니다.

float floatValue = 3.14f;
int intValue = (int) floatValue;
System.out.println(intValue); // 출력 결과: 3

2. Math.round() 메서드 사용

Math.round() 메서드를 사용하여 소수점 이하를 반올림한 후 int로 형변환할 수 있습니다.

float floatValue = 3.14f;
int intValue = Math.round(floatValue);
System.out.println(intValue); // 출력 결과: 3

3. Float.intValue() 메서드 사용

Float 클래스의 intValue() 메서드를 사용하여 float을 int로 변환할 수 있습니다.

float floatValue = 3.14f;
int intValue = Float.floatToIntBits(floatValue);
System.out.println(intValue); // 출력 결과: 1078523331

4. Float.intValue() 메서드와 Float.floatToIntBits() 메서드 사용

Float 클래스의 floatValue() 메서드와 floatToIntBits() 메서드를 사용하여 float을 int로 변환할 수 있습니다.

float floatValue = 3.14f;
int intValue = Float.floatToIntBits(floatValue);
System.out.println(intValue); // 출력 결과: 1078523331

5. Double.intValue() 메서드 사용

Double 클래스의 intValue() 메서드를 사용하여 double을 int로 변환할 수도 있습니다. 이 방법은 데이터 손실이 발생할 수 있습니다.

double doubleValue = 3.14;
int intValue = (int) doubleValue;
System.out.println(intValue); // 출력 결과: 3

6. String을 int로 변환

String으로 변환한 후 Integer.parseInt() 메서드를 사용하여 int로 변환할 수도 있습니다. 이 방법은 데이터 손실이 없습니다.

float floatValue = 3.14f;
int intValue = Integer.parseInt(String.valueOf(floatValue));
System.out.println(intValue); // 출력 결과: 3