Skip to content

optimize DoubleConverter #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,11 @@
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Converts between a double and a String.
*/
public class DoubleConverter {
private static final Pattern DECIMAL_PATTERN = Pattern.compile("-?\\d*(\\.\\d*)?");
private static final ThreadLocal<DecimalFormat[]> THREAD_DECIMAL_FORMATS = new ThreadLocal<>();

/**
Expand Down Expand Up @@ -92,13 +89,25 @@ public static String convert(double d, int padding) {
*/
public static double convert(String value) throws FieldConvertError {
try {
Matcher matcher = DECIMAL_PATTERN.matcher(value);
if (!matcher.matches()) {
throw new NumberFormatException();
}
return Double.parseDouble(value);
return parseDouble(value);
} catch (NumberFormatException e) {
throw new FieldConvertError("invalid double value: " + value);
}
}

private static double parseDouble(String value) {
if(value.length() == 0) throw new NumberFormatException(value);
boolean dot = false; int i = 0;
char c = value.charAt(i);
switch (c) {
case '-': i++; break;
case '+': throw new NumberFormatException(value);
}
for (; i < value.length(); i++) {
c = value.charAt(i);
if (!dot && c == '.') dot = true;
else if (c < '0' || c > '9') throw new NumberFormatException(value);
}
return Double.parseDouble(value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ public void testIntegerConversion() throws Exception {
} catch (FieldConvertError e) {
// expected
}

try {
//Sequence of digits without commas or decimals and optional sign character (ASCII characters "-" and "0" - "9" ).
//FIXME
IntConverter.convert("100");
fail();
} catch (FieldConvertError e) {
// expected
}
}

public void testDoubleConversion() throws Exception {
Expand Down