Java

[Java] 소수점 반올림, 절삭, 돈 표기 방법:세번째 위치마다 콤마(,) 찍기

double 타입의 데이터 또는 float형 데이터를 반올림하거나 버려야할(절삭) 경우가 있다. 가장 쉬운 방법은 Math 클래스를 사용하는 방법이다.  예제를 보자. 반올림이 필요한 경우 round()메소드를 사용하면된다. 반대로 절삭은 floor()메소드를 사용하자. round()메소드는 소수점 첫번째 자리에서 반올림 처리가 된다.  따라서 결과는 정수값이 반환된다.

package edu.sample;

import java.text.DecimalFormat;

public class Money {
	
	public static void main(String[] args) {
		
		double a = 80.45;
		
		//버림 (절삭)
		System.out.println(Math.floor(a));
		
		//절대값
		System.out.println(Math.abs(a));
		
		//올림
		System.out.println(Math.ceil(a));
		
		//반올림
		System.out.println(Math.round(a)); 
	} 

}

■출력결과


round()메소드를 사용하여 소수점 셋째자리에서 반올림해보자. 소수점 둘째자리까지 표기하기 위한 방법이다. 100을 곱한 후 100.0으로 나누기 하면 얻을 수 있다. 소수점 세번째자리까지 표기하고 싶다면, 1000을 곱한 후 1000.0으로 나누기 하면 얻을 수 있다.

package edu.sample;

import java.text.DecimalFormat;

public class Money {
	
	public static void main(String[] args) {
    
	double e = 2.71828;
	System.out.println(Math.round(e*100)/100.0); //소수점 둘째자리까지 표기
    
    //소수점 셋째자리까지 표기
    //System.out.println(Math.round(e*1000)/1000.0); 
 
	} 

}

■출력결과


 

소수점 n번째 자리까지 남기는 메소드 만들어서 호출하여 사용할 수 있다. 

package edu.sample;

public class Money {
	
	public static void main(String[] args) {

		double b = 2.71858;
		getMathAround(b, 0);
		getMathAround(b, 1);
		getMathAround(b, 2);
		getMathAround(b, 3);
 
	} 
	
	
	public static double getMathAround(double targetValue , int position) {
		 double ndb = Math.pow(10.0, position);
		 
		 System.out.println(Math.round(targetValue * ndb) / ndb); 
	       
		return (Math.round(targetValue * ndb) / ndb);
	}

}

■출력결과


String.format()을 사용하는 방법도 있다. Math.round()메소드와 같이 소수점 n번째 자리에서 반올림하여 나타낼 수 있다.  이 둘의 차이점은 Math.round()메소드는 소수점 아래가 0일경우 절삭하지만 String.format()은 절삭하지 않고 소수점자리수를 유지해준다. 

package edu.sample;

public class Money {
	
	public static void main(String[] args) {
		
		double money = 3000.000;
        
		System.out.println(Math.round(money*1000)/1000); //결과 : 3000
        
		System.out.println(String.format("%.3f", money)); //결과 : 3000.000	 
 
	}  

}

■출력결과


■ 돈 표기 방법

package edu.sample;

import java.text.DecimalFormat;

public class Money {
	
	public static void main(String[] args) {		
		
		// 돈 표시 : 세번째 위치마다 콤마(,)를 표시
		DecimalFormat formatter = new DecimalFormat("#,##0");
		int money = 10000000;
		String tmp = formatter.format(money); 
		System.out.println(tmp);
		
		// 소수점 이하 2번째자리까지 표시하며 소수점 이하가 없을 경우 .00으로 표시한다.
		DecimalFormat formatter2 = new DecimalFormat("#,##0.00");
		double money2 = 100000000d;
		tmp = formatter2.format(money2); 		
		System.out.println(tmp);
		
		// 소수점 이하 2번째자리까지 표시하며 소수점 이하가 없을 경우 표시하지 않는다.
		DecimalFormat formatter3 = new DecimalFormat("#,##0.##");
		tmp = formatter3.format(money2); 
		System.out.println(tmp); 
		
	} 

}

■출력결과


 

Leave a Reply

error: Content is protected !!