ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java Locale 처리
    개발입문/JAVA 2017. 9. 14. 23:55


    HackerRank Java 
    Java Currency Formatter
    > https://www.hackerrank.com/challenges/java-currency-formatter




    1. NumberFormat class 

    코드는 로컬 관습이나 환경과 독립적으로 구현하고 
    NumberFormat 클래스가 로컬라이제이션을 위한 숫자 포맷, 파싱 기능을 제공한다.
    >> 즉, 코드는 로컬라이제이션에 대해 크게 신경을 안 써도 된다는 얘기!!!

    NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.

    To format a number for the current Locale, use one of the factory class methods:

     myString = NumberFormat.getInstance().format(myNumber);


    Number 에 대해 지역마다 달라질 수 있는 정보는 숫자, 통화, % 표현등이 있다.
    NumberFormat 클래스는 default 로컬정보에 대해 위의 각 포맷을 세팅할 수 있는 메소드를 제공하고 있다.
    또는 원하는 로컬환경을 직접 지정할 수도 있다.

    NumberFormat.getInstance(myLocale)
    NumberFormat.getInstance(Locale.KOREA) NumberFormat.getNumberInstance(Locale.KOREA) NumberFormat.getCurrencyInstance(Locale.KOREA)  NumberFormat.getPercentInstance(Locale.KOREA)




    2. 팩토리 클래스 메소드

    그런데 NumberFormat 은 abstract 추상클래스인데,
    .getInstance() 메소드가 있다! 인스턴스화한 객체를 사용할 수 있다. 
    이런 것들을 팩토리 클래스 메소드라고 한다.

    팩토리는 공장처럼 객체를 찍어내는 (인스턴스화하는) 메소드라는 의미이다.

    To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's factory methods, such as getInstance(). In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat. If you need to customize the format object, do something like this:


      NumberFormat nf = NumberFormat.getInstance(loc);

    if(nf instanceof DecimalFormat) {

    ((DecimalForamt) f).setDecimalSeparatorAlwaysShown(true);

    }



    3. Locale 설정

    Locale 을 직접 설정할 수 있다.
    Locale 클래스는 특정 지역학적, 정치적, 문화적 지역 정보에 맞추어 정보 표현방식을 가공한다.  (엄청 섬세한 녀석...)
    >> A Locale object represents a specific geographical, political, or cultural region. 

    Locale 정보는 language, script, country, variant, extensions 가 있는데, 우리는 주로 언어와 국가만 신경쓰면 된다.
    Creating a Locale 항목에 잘 나와있다.

    1) Locale 을 언어, 국가 팩 조합해서 생성
    2) 더 상세한 정보를 조합하려면 Locale.Builder 클래스로 세팅
    3) forLangueTag(String languageTag) 로
    3) Locale.US 상수로

    다행히 우리나라는 Locale 에서 상수로 지정하고 있다.
    KOREA, KOREAN (생각보다 몇개 없어서 되어있는게 신통방통 하다.)
    그리고 US, CHINA, FRANCE, JAPAN 정도는 상수로 제공되고 있다.

    그 외  다른 나라의 경우에는 Locale을 조합해서 만들어주어야 한다.
    언어코드나 나라코드는 ISO 규격에서 찾아줘야 한다.

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


    '개발입문 > JAVA' 카테고리의 다른 글

    Regular Expression 정규표현식(1) Character  (0) 2017.09.19
    정규표현식 Regular Expression  (0) 2017.09.19
    Wrapper Class 래퍼클래스  (0) 2017.09.12
    Numeric Datatype  (0) 2017.09.10
    Java String Formatting  (0) 2017.09.10

    댓글

Designed by Tistory.