float가 이상해요.

Tags:

안녕하세요 java의 소수점 이하 반올림시 이상한 점이 발견되어 글을 올립니다.

문제는 1.175의 반올림시 문제 입니다. 소스와 결과치를 같이 올리겠습니다…

1. 테스트1

import java.text.*;
public class FormatTest{

  public static void main(String args[]){
   
   float percent41 = 1.175f;
   float percent51 = 11.175f;
  
  
   float percent6 = 0.17501f;
   float percent7 = 0.1850f;
  

   DecimalFormat format1 = new DecimalFormat(“###.00”);
  
  
   System.out.println(“1.175f: “+format1.format(percent41));
   System.out.println(“11.175f: “+format1.format(percent51));
  
   System.out.println(“0.17501f: “+format1.format(percent6));
   System.out.println(“0.1850f: “+format1.format(percent7));
  
  }
}

— > 결과치::
1.175f: 1.17     <- 결과치가 이상합니다. 11.175f: 11.18 0.17501f: .18 0.1850f: .19 2.테스트2 import java.text.*; public class FormatTest1{     public static void main(String args[]){       float percent41 = 1.175f;    float percent51 = 11.175f;          float percent6 = 0.17501f;    float percent7 = 0.1850f;         // DecimalFormat format = new DecimalFormat("###.000");   // DecimalFormat format1 = new DecimalFormat("###.00");          System.out.println("1.175f: "+aaa(percent41));    System.out.println("11.175f: "+aaa(percent51));       System.out.println("0.17501f: "+aaa(percent6));    System.out.println("0.1850f: "+aaa(percent7));      }       public static float aaa(float unrounded){    return Math.round(unrounded*100)/100f;   }  } 결과치: 1.175f: 1.17     <- 결과치가 이상합니다. 11.175f: 11.18 0.17501f: .18 0.1850f: .19 그외 php에 비슷하게 하여 테스트 해 봤는데요 1.175를 소수점 이하 2자리까지 뿌리면 1.18이 나옵니다. 원인을 알수가 없네요.. 제목 : Re: float 연산을 정확하게 하는 방법 글쓴이: 서민구(guest)  2005/06/15 19:39:17 조회수:66 줄수:28   부동소수 연산을 정확하게 하는 방법은, float를 안쓰는겁니다. 또, 자바가 이상한게 아니라 IEEE 754가 원래 그렇습니다. http://javaservice.net/~java/bbs/read.cgi?m=resource&b=qna2&c=r_p&n=1118716242&p=1&s=t#1118716242 http://docs.sun.com/source/806-3568/ncg_goldberg.html 참고하시구요. 아래와 같이 BigDecimal쓰세요 import java.math.*; public class FormatTest1{   public static void main(String args[]){    BigDecimal p1 = new BigDecimal("1.175");    BigDecimal p2 = new BigDecimal("11.175");    System.out.println(p1.toString() + " => ” + p1.setScale(2, BigDecimal.ROUND_HALF_UP));
   System.out.println(p2.toString() + ” => ” + p2.setScale(2, BigDecimal.ROUND_HALF_UP));
  }
}

[결과]
1.175 => 1.18
11.175 => 11.18

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *