How do I go from a DecimalFormat (String) to Double?

0

I want to work with the decimal part of a number, for example 123.332341 I just want to get the ' .332341 ' only with 3 digits after the period, like this: '< em> .332 ' I use DecimalFormat formato = new DecimalFormat(".###"); (which I found on the internet) I do the test to check the result, and it does not convert from this type of data a double "modified"

double numero = .332341;
String modificar = formato.format(numero); //debe quedar .332
double nuevo = Double.parseDouble(formato.format(modificar)); //no convierte
System.out.println(nuevo); //nada

How or what other option can I use to achieve the goal of bringing only 3 digits? Error:

  Exception en Thread "main" java.lang.NumberFormatException: For input string: ",332"
    ...
    at java.lang.Double.parseDouble(Double.java:538)
    at Binario.Binario.main(Binario.java:30)

    
asked by Jose Luis 23.02.2017 в 03:30
source

2 answers

1

To limit the String from double to 3 digits, but using a decimal point, you can use:

// usar Locale.US en el formato garantiza que se usa un punto decimal en vez de un coma
String numeroString = String.format(Locale.US,"%.3f", numero);
// eso devuelve .332 para el valor que usaste
Double nuevo = Double.parseDouble(numeroString);

To modify the format, you can review the documentation java.util.Formatter .

In your case you can not instantiate DecimalFormat with the constructor you use. You had to use

df = new DecimalFormat(".###", new DecimalFormatSymbols(Locale.US));

or

df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);

and then apply the pattern with applyPattern() . If not, you work with your locality by default (of the virtual machine where your program runs). That makes your code vulnerable to fail if it does not run in the same location where it was developed.

Just in case you do not want to use a String to cut your number to 3 digits, you can use Math as well:

// redondear matemáticamente 
Double nuevo = Math.round(numero*1000D)/1000D;
// redondear abajo
Double nuevo = Math.floor(numero*1000D)/1000D;
// redondear arriba
Double nuevo = Math.ceil(numero*1000D)/1000D;
    
answered by 23.02.2017 / 04:32
source
0

1st. Depends on the operating system you are using ...
 The problem is the format with which the operating system reads this line and the delimiter it uses. To solve the problem, your operating system thinks that the comma delimits the decimals so you can do 2 things:

Option 1

double nuevo = Double.parseDouble(formato.format(modificar).replace(",","."))

Option 2

I guess it's Windows?
You have to go to - panel de control > Reloj, idioma > Región > config adicional .

Here you have to see the decimal symbol and if you have a " . " change it to " , ".

    
answered by 23.02.2017 в 03:48