티스토리 뷰

개발을 하다보면 String <-> Number(int, float, double)로 형변환을 할 일이 많다.

전에는 이런 형변환을 아래와 같이 parse() 함수를 이용해서 수행했었다.

String s = "3";
Integer.parseInt(s);
Float.parseFloat(s);
Double.parseDouble(s);

 

 

s가 빈 문자가 아니라는 확신이 있다면 위 코드는 문제가 없다.

하지만 만일 빈 문자가 들어올 수도 있는 값을 Number 타입으로 변경해야한다면 아래와 같은 에러가 발생한다.

String s = ""; // 또는 s 등과 같은 숫자가 아닌 문자
Integer.parseInt(s);

java.lang.NumberFormatException: For input string: ""

 

또한 숫자로 변환할 수 없는 문자가 들어왔을 경우에도 NumberFormatException 에러가 발생한다.

 

 

그렇다면 매 번 형 변환을 하기 전에 문자를 숫자로 변환할 수 있는지 유효성 체크를 하거나 try-catch로 묶어서 따로 형반환에 대해 처리를 해줘야할까?

솔직히 그건 너무 번거롭고 코드가 길어지게 만들고 지저분하게 만든다.

int n;
try {
	n = Integer.parseInt(s);
} catch (NumberFormatException e) {
	n = 0;
}

 

 

NumberUtils.to${NumberType}

이와 같이 문자 -> 숫자로 형변환 시 에러가 발생하면 설정한 default 값으로 숫자를 반환시킬 수 있는 함수를 제공하는 NumberUtils라는 객체가 있다.

NumberUtils에 있는 toInt() 함수를 예시로 살펴보면 아래와 같다.

public static int toInt(String str) {
    return toInt(str, 0);
}

public static int toInt(String str, int defaultValue) {
    if (str == null) {
        return defaultValue;
    } else {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException var3) {
            return defaultValue;
        }
    }
}

 

 

핵심인 부분을 보면 문자를 받아서 문자가 null일 경우와 try-catch 안에서 형변환을 하는데 에러가 발생하면 defaultValue를 반환해준다.

함수 안에 있는 'Integer.parseInt()' 부분은 문자 -> 숫자 형변환을 할 때 익히 봐왔던 것이다.

if (str == null) {
    return defaultValue;
} else {
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException var3) {
        return defaultValue;
    }
}

 

 

NumberUtils 코드를 보면 deaultValue 파라미터를 받지 않는 함수에서는 아예 NumberUtils에서 defaultValue를 0으로 설정해서 동작하고 있다.

즉, 문자를 받아서 숫자로 형변환을 할 때는 번거롭게 try-catch나 유효성 검사를 할 필요 없이 NumberUtils를 사용하면 된다.

String s = "s";
NumberUtils.toInt(s); // 0

 

 

 

✋ NumberUtils

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html

 

NumberUtils (Apache Commons Lang 3.12.0 API)

Convert a String to a Integer, handling hex (0xhhhh) and octal (0dddd) notations. N.B. a leading zero means octal; spaces are not trimmed. Returns null if the string is null.

commons.apache.org

 

 

 

 

 

반응형

'Java' 카테고리의 다른 글

Checked Exception vs UnChecked Exception  (0) 2021.10.12
custom annotation(커스텀 어노테이션) 만들기  (0) 2021.10.08
JRE와 JDK 차이점  (0) 2021.10.04
Java 8부터 지원되는 Stream API  (0) 2021.09.14
제너릭(Generic)이란?  (0) 2021.09.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함