2019년 5월 28일 화요일

Java NumberFormat 이용하여 각 나라의 통화(currency) 출력하기




* NumberFormat 클래스를 이용하여 통화 형식 맞추기



NumberFormat API: https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html
Locale API: https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html
IANA Language Subtag Registry: https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
 

 NumberFormat 클래스는 숫자의 parsing , 숫자의 포맷을 세팅하고  기능을 제공한다.
 각 나라의 통화들은 NumberFormat 클래스를 이용하여 표현할 수 있다.

 NumberFormat 클래스는 추상클래스이기 때문에 new로 생성할 수 없고, Calendar 클래스와 마찬가지로 getInstance() 와 같이 객체를 가져오는 메소드를 호출해야 한다.

 아래는 NumberFormat 객체를 가져오는데 Locale 국가코드를 인자로 넣어 해당 국가의 통화포멧을 설정할 수 있다. 


NumberFormat u = NumberFormat.getCurrencyInstance(Locale.US);


 Korea 통화는 Locale 클래스 안에 내장되어 있지만 인도는 Locale이 내장되어 있지 않다.
 India 같은 경우에는 Locale 클래스의 생성자를 이용하여 언어와 국가를 설정해주어야 하는데, 생성자에 들어가는 인자값에 대한 설명은 Locale class API 문서에 잘 나와있다.



country (region)
ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. You can find a full list of valid country and region codes in the IANA Language Subtag Registry (search for "Type: region"). The country (region) field is case insensitive, but Locale always canonicalizes to upper case.
Well-formed country/region values have the form [a-zA-Z]{2} | [0-9]{3}
Example: "US" (United States), "FR" (France), "029" (Caribbean)



IANA Language Subtag Registry 로 검색을 하여 인도의 subtag 값을 찾아서 넣으면 된다.

 NumberFormat i = NumberFormat.getCurrencyInstance(new Locale("en","IN"));



아래는 나라 별 통화의 기호를 출력해보는 예제이다.




public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();

        NumberFormat u = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat i = NumberFormat.getCurrencyInstance(new Locale("en","IN"));
        NumberFormat c = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat f = NumberFormat.getCurrencyInstance(Locale.FRANCE);
        String us = u.format(payment);
        String india = i.format(payment);
        String china = c.format(payment);
        String france = f.format(payment);

        System.out.println("US: " + us);
        System.out.println("India: " + india);
        System.out.println("China: " + china);
        System.out.println("France: " + france);
    }
}

댓글 없음:

댓글 쓰기