Подтвердить что ты не робот

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

В результате получается Exception:

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

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

4b9b3361

Ответ 1

Используйте java.text.NumberFormat:

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

Ответ 2

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

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);

Ответ 3

Как указывает E-Riz, NumberFormat.parse(String) анализирует "1,23abc" как 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();
}

Ответ 4

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

    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".

Ответ 5

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

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;
        }
    }
}

Ответ 6

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

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

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

Ответ 7

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

Ответ 8

Это выполнит задание:

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