2013-06-11 3 views
2

Java 1.6을 사용하고 숫자를 형식화하기 위해 java.text.DecimalFormat을 사용하고 있습니다. 예를10 진수 형식 null 처리

DecimalFormat df = new DecimalFormat(); 
    df.setPositivePrefix("$"); 
    df.setNegativePrefix("(".concat($)); 
    df.setNegativeSuffix(")"); 
    df.setMaximumFractionDigits(2); 
    df.setMinimumFractionDigits(2); 
    df.setGroupingSize(3); 

    df.format(new java.math.BigDecimal(100); 

내 응용 프로그램 충돌 할 때마다 통과 null

Error: cannot format given object as a number 

내 질문은 df.format(null)하려면 어떻게 df.format() 기능에 null 값을 처리 할 수 ​​있습니까?

null을 df.format() 함수에 전달하고 싶습니다. 위의 오류 대신 0.00을 반환하려고합니다.

감사합니다 당신에게

감사합니다,

Ankush

+0

이것은 분명하지 않습니다. 위의 코드에서'df.format'에'null '을 넘기고 있습니까? –

+0

부화장 연산자를 사용하여 value와 같은 값의 null 조건을 확인하십시오! = null? 값 : 0.00 –

+0

@Oli, df.format (Value_to_be_formatted)가 JasperReports (여기서 장면이 아닌)에서 호출 중입니다. null 값을 받아들이도록 format() 메서드를 변경하고 null 입력의 경우 0을 반환하고 싶습니다. –

답변

9

내 응용 프로그램 충돌 할 때마다

예, 그것은 것

에 패스 null 값.

예외 : 즉, documented 행동의IllegalArgumentException-numbernull 여부 Number의 인스턴스의 경우는.

다음 :

I() 함수 df.format에 null을 전달하고자하고 대신 위의 오류의 0.00를 반환 할 것입니다.

아니요, 작동하지 않습니다. 작동하지 않는 것으로 기록되어 있습니다. null을 넘기지 마십시오. 탐지하기가 쉽습니다. 그래서 당신은이를 사용할 수 있습니다

String text = value == null ? "0.00" : df.format(value); 

또는

String text = df.format(value == null ? BigDecimal.ZERO : value); 
+0

+1 할 수 있으면 +1이 두 번됩니다;) –

+0

df.format (value == null? BigDecimal.ZERO : value); 이것은 바로 지금 우리가 수행하고있는 작업입니다. null을 허용하고 0을 반환하도록 형식 함수를 오버로드 할 수 있다면 방황하고있었습니다. –

+0

@AnkushChhabra : 아니요. 여러분이'DecimalFormat'을 직접 확장하고'format'을 오버라이드 할 수 있으며 기존 계약을 깨뜨릴 수는 있습니다.하지만 그건 정말 나쁜 생각입니다. 그냥 정적 헬퍼 메소드에 넣으면 괜찮을거야. –

1

(제대로 존 소총에 의해 지적)에 DecimalFormat는 API를 끊을 확장,하지만 당신은 주어진에 DecimalFormat를 래핑 자신의 형식 구현할 수 :

를 하나는 null이 아닌 것으로 toAppendTopos을 필요로
public class OptionalValueFormat extends Format { 

    private Format wrappedFormat; 

    private String nullValue; 

    public OptionalValueFormat(Format wrappedFormat, String nullValue) { 
    this.wrappedFormat = wrappedFormat; 
    this.nullValue = nullValue; 
    } 

    @Override 
    public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { 
    if (obj == null) { 
     // Just add our representation of the null value 
     return toAppendTo.append(nullValue); 
    } 

    // Let the default format do its job 
    return wrappedFormat.format(obj, toAppendTo, pos); 
    } 

    @Override 
    public Object parseObject(String source, ParsePosition pos) { 
    if (source == null || nullValue.equals(source)) { 
     // Unwrap null 
     return null; 
    } 

    // Let the default parser do its job 
    return wrappedFormat.parseObject(source, pos); 
    } 

} 

이, java.text.Format의 API를 중단하지 않을 것입니다. OptionalValueFormat의 사용에 대한

예 :

DecimalFormat df = ... 

OptionalValueFormat format = new OptionalValueFormat(df, "0.00"); 
System.out.println(format.format(new java.math.BigDecimal(100))); 
System.out.println(format.format(null)); 

결과 :

100 
0.00 
나는 당신이이 클래스를 추가해야합니다, 그래서 이러한 형식의 래퍼를 제공합니다 알고있는 헬퍼 라이브러리의

불행하게도 없음 귀하의 프로젝트.