separar punto por miles ingresar declarar decimales como coma java

java - punto - La mejor manera de parseDoble con coma como separador decimal?



replace coma por punto java (8)

Como señala E-Riz, NumberFormat.parse (String) analiza el "1,23abc" como 1.23. Para tomar la entrada completa, podemos usar:

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

Lo siguiente está dando lugar a una Exception :

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

¿Hay una mejor manera de analizar "1,234" para obtener 1.234 que: p = p.replaceAll(",","."); ?


Este es el método estático que uso en mi propio código:

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://.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; } } }


Esto haría el trabajo:

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


Por supuesto, necesita utilizar la configuración regional correcta. This pregunta ayudará.


Puede usar esto (la configuración regional francesa tiene , para el separador decimal)

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

O puede usar java.text.DecimalFormat y establecer los símbolos apropiados:

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


Si no conoce la configuración regional correcta y la cadena puede tener un separador de mil, podría ser un último recurso:

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(",", "."));

Tenga en cuenta: esto analizará felizmente cadenas como "R 1 52.43,2" a "15243.2".


Use java.text.NumberFormat :

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


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

... es muy rápido ya que busca la matriz de caracteres subyacente en una base de char por char. Las versiones de reemplazo de cadenas compilan un RegEx para evaluar.

Básicamente reemplazar (char, char) es aproximadamente 10 veces más rápido y dado que estarás haciendo este tipo de cosas en código de bajo nivel, tiene sentido pensar sobre esto. El optimizador de Hot Spot no lo resolverá ... Ciertamente no lo hace en mi sistema.