프로그래밍/Java

자바 소수점 사용하기

미냐님 2020. 3. 30. 22:36
728x90

소수점 사용하기

  • Math.round() 를 이용

    • Math.round 함수의 역할은 소수점 첫번째 자리를 참조하여 반올림을 시키는 것이다.
      그러나 소수점 몇 번째자리까지 필요할 때 바로 위의 방식을 쓰자
      67.655*100을 하면 6765.5가 된다.
      여기서 round가 적용되면 6766이 된다.
      다시 100.0 여기서 .0을 붙여야 실수로 적용이 되어 나온다.
      하면 67.66이 된다!! 세번째 자리에서 반올림하여 나오는것이다.
      100이라는 값을 1000으로 하면 네번째자리에서 반올림이 되고
      10을 하면 두번째자리이다.
public class Round{
   public static void main(String args[]){
      System.out.println(Math.round(67.655*100)/100.0);
   }
}
  • System.out.printf() 혹은 format() 을 이용
    • 이때 뒤에 들어가는 파라메터에 정수를 입력하게 되면?
      IllegalFormatConversionException 가 발생한다.
System.out.printf("%.2f", 33.3333); //결과값 33.33
  • String.format() 을 이용
float f = 0.55555f

String str = String.format("%.2f", f);

System.out.println("str = " + str);

str = 0.56
  • DecimalFormat 을 이용
float f 의 소수점 두번째 자리까지의 값을 String str 로 변환합니다.

float f = 0.55555f

DecimalFormat format = new DecimalFormat(".##");

String str = format.format(f);

System.out.println("str = " + str); //str = 0.55
728x90