자바 NumberFormat, Locale 클래스(나라별 화폐 표시)

2019. 3. 27. 22:22알고리즘문제/Hackerrank

미국, 인도, 중국, 프랑스 등 나라별 화폐 표시를 해보고자 한다. 

금액을 담은 double변수의 포맷을 바꿔 보여주면 된다. 

 

이를 위해

NumberFormat 클래스는 수에 대한 전반적인 포맷 기능을 제공한다. 

getCurrencyInstance 메소드를 사용해 클래스를 사용할 수 있으며 바로 화폐 단위를 표시한다. 

따로 국가 설정을 안할 시 Default는 한국이다. 

 

국가 설정 시 Locale 객체를 사용한다.

 

public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
    double payment = scanner.nextDouble();
    scanner.close();
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

    System.out.println("US: " + nf.format(payment));

    Locale indiaLocale = new Locale("en", "IN");
    nf = NumberFormat.getCurrencyInstance(indiaLocale);
    System.out.println("India: " + nf.format(payment));

    nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
    System.out.println("China: " + nf.format(payment));

    nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
    System.out.println("France: " + nf.format(payment));
}

 

* 인도의 경우 기본 국가로 설정되어 있지 않기 때문에

Locale 클래스를 이용해 임의의 객체를 생성해 준 후 이용한다. 

* new Locale(String language, String country)

* en : English / IN : INDIA 

 

 

 

참조

- NumberFormat (Java8 Docs)

https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getCurrencyInstance-java.util.Locale-

 

NumberFormat (Java Platform SE 8 )

Parses text from a string to produce a Number. The method attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all char

docs.oracle.com

 

- Locale (Java8 Docs)

https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html

 

Locale (Java Platform SE 8 )

getDisplayLanguage public String getDisplayLanguage(Locale inLocale) Returns a name for the locale's language that is appropriate for display to the user. If possible, the name returned will be localized according to inLocale. For example, if the locale is

docs.oracle.com

- Locale 사용에 대한 설명

https://jhamin0511.tistory.com/5

 

[Android/Java] Locale 클래스 기초

[1] Local 클래스 (https://developer.android.com/reference/java/util/Locale.html) 간단히 말하면 지역의 [언어][나라] 등의 정보를 담고 있는 클래스이다. [2] Local 클래스 사용 사용방법은 인스턴스화 방법..

jhamin0511.tistory.com

 

'알고리즘문제 > Hackerrank' 카테고리의 다른 글

자바 Pattern 클래스  (0) 2019.04.01
자바_정규표현식(matches, pattern)  (0) 2019.04.01
자바 SortedSet, TreeSet  (0) 2019.03.29
자바(Java)_Arrays.sort 메소드 활용  (0) 2019.03.27
자바8 날짜 클래스 LocalDate  (0) 2019.03.27