[Java] 소수점 처리 방법

Updated:

Math.rount() 와 String.format() 함수

Math.rount()


  • 실수의 소수점 첫번째 자리를 반올림하여 정수로 리턴
  • 사용법

      double pie = 3.14159265358979;
      System.out.println(Math.round(pie)); //결과 : 3
      System.out.println(Math.round(pie*100)/100.0); //결과 : 3.14
      System.out.println(Math.round(pie*1000)/1000.0); //결과 : 3.142
    
    

String.format()


  • 실수의 소수점 첫번째 자리를 반올림하여 정수로 리턴
  • 사용법

      double pie = 3.14159265358979;
      double money = 4424.243423;
      System.out.println(String.format("%.2f", pie)); //결과 : 3.14
      System.out.println(String.format("%.3f", pie)); //결과 : 3.142
      System.out.println(String.format("%,.3f", money)); //결과 : 4,424.243
    

Math.round() 와 String.format() 비교


  • Math.round()함수는 소수점아래가 0일경우 절삭하지만 String.format은 절삭하지 않고 그대로 리턴
  • 사용법

      ddouble money = 5000.000;
      System.out.println(Math.round(money*1000)/1000); //결과 5000
      System.out.println(String.format("%.3f", money)); //결과 : 5000.00
    

참고


  • 자바의 정석

Tags:

Categories:

Updated:

Leave a comment