Лучший способ разбора с запятой в качестве десятичного разделителя?



следующее приводит к Exception:



String p="1,234";
Double d=Double.valueOf(p);
System.out.println(d);


есть ли лучший способ для разбора "1,234" и 1.234 чем: p = p.replaceAll(",",".");?

212   8  

8 ответов:

использовать java.текст.NumberFormat:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

вы можете использовать это (французский язык имеет , для десятичного разделителя)

NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
nf.parse(p);

или вы можете использовать java.text.DecimalFormat и установите соответствующие символы:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

Как указывает E-Riz, NumberFormat.разбор (строка) разбор "1,23 abc" как 1.23. Чтобы взять весь вход мы можем использовать:

public double parseDecimal(String input) throws ParseException{
  NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
  ParsePosition parsePosition = new ParsePosition(0);
  Number number = numberFormat.parse(input, parsePosition);

  if(parsePosition.getIndex() != input.length()){
    throw new ParseException("Invalid input", parsePosition.getIndex());
  }

  return number.doubleValue();
}

Если вы не знаете правильный язык и строка может иметь тысячу разделителей это может быть последним средством:

    doubleStrIn = doubleStrIn.replaceAll("[^\d,\.]++", "");
    if (doubleStrIn.matches(".+\.\d+,\d+$"))
        return Double.parseDouble(doubleStrIn.replaceAll("\.", "").replaceAll(",", "."));
    if (doubleStrIn.matches(".+,\d+\.\d+$"))
        return Double.parseDouble(doubleStrIn.replaceAll(",", ""));
    return Double.parseDouble(doubleStrIn.replaceAll(",", "."));

имейте в виду: это будет счастливо разобрать строки,такие как "R 1 52.43, 2" до "15243.2".

это статический метод, который я использую в моем собственном коде:

public static double sGetDecimalStringAnyLocaleAsDouble (String value) {

    if (value == null) {
        Log.e("CORE", "Null value!");
        return 0.0;
    }

    Locale theLocale = Locale.getDefault();
    NumberFormat numberFormat = DecimalFormat.getInstance(theLocale);
    Number theNumber;
    try {
        theNumber = numberFormat.parse(value);
        return theNumber.doubleValue();
    } catch (ParseException e) {
        // The string value might be either 99.99 or 99,99, depending on Locale.
        // We can deal with this safely, by forcing to be a point for the decimal separator, and then using Double.valueOf ...
        //http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator
        String valueWithDot = value.replaceAll(",",".");

        try {
          return Double.valueOf(valueWithDot);
        } catch (NumberFormatException e2)  {
            // This happens if we're trying (say) to parse a string that isn't a number, as though it were a number!
            // If this happens, it should only be due to application logic problems.
            // In this case, the safest thing to do is return 0, having first fired-off a log warning.
            Log.w("CORE", "Warning: Value is not a number" + value);
            return 0.0;
        }
    }
}
Double.parseDouble(p.replace(',','.'))

...очень быстро, поскольку он ищет базовый массив символов на основе char-by-char. Строка replace versions компилирует регулярное выражение для оценки.

в основном replace (char,char) примерно в 10 раз быстрее, и поскольку вы будете делать такие вещи в низкоуровневом коде, имеет смысл подумать об этом. Оптимизатор горячих точек не поймет этого... Конечно, не в моей системе.

вам, конечно,нужно использовать правильный язык. этой вопрос поможет.

для:

Double.parseDouble(p.replace(',','.')); 

Comments

    Ничего не найдено.