JDK-8180188 : DecimalFormat not throwing any exception for invalid pattern
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.text
  • Priority: P4
  • Status: Resolved
  • Resolution: Duplicate
  • Submitted: 2017-05-11
  • Updated: 2017-05-31
  • Resolved: 2017-05-31
Related Reports
Duplicate :  
Relates :  
Description
A DESCRIPTION OF THE PROBLEM :

As per the API specification of DecimalFormat  "A DecimalFormat pattern contains a positive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, numeric part, and suffix.", but it does not throw any exception when an invalid pattern is used, such as "(#(#)" (numeric part / special character after suffix). Below are some examples of similar invalid patterns and the output given by DecimalFormat

1. formatting -3456.349347 with pattern (#(#) (invalid positive sub-pattern) returns -(3456()
2. formatting -3456.349347 with pattern #,##0.0#;(#(#) (invalid negative sub-pattern) returns (3,456.35()

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :

Execute below code snippet
=======================================
DecimalFormat format = new DecimalFormat("(#(#)");
double number = -3456.349347;
System.out.println(format.format(number));
=======================================

Expected
Throw Exception

Actual
Returns unpredictable results
-(3456() for (#(#) and (3,456.35() for #,##0.0#;(#(#)

REPRODUCIBILITY :
This bug can be reproduced always.
Comments
Duplicate of 4503190
31-05-2017

Unlike mentioned in the api specification ("A DecimalFormat pattern contains a positive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, numeric part, and suffix."), the current implementation keeps parsing the subpattern for numeric part even after the suffix is encountered. I think the above pattern "(#(#)" is an invalid one, because no numeric character (unquoted special character) e.g. #, 0 etc. must be allowed after the suffix is encountered within a subpattern. Attaching a possible fix for this issue, but fixing it and throwing a new Exception may raise the backward compatibility issue.
23-05-2017