Limit the number of decimals

0

If I want to enter the price $ 6.00 How do I limit the number of decimals?

Using:

 dts.setPrecio(Double.parseDouble(txtprecioExamen.getText()));

    
asked by Esme 05.05.2018 в 11:55
source

1 answer

0

Use a DecimalFormatter :

double numero = 0.9999999999999;
DecimalFormat numeroFormateado = new DecimalFormat("#.00");
System.out.println(numeroFormateado.format(numero));

Then based on your code it would be something like this:

Double valor= Double.parseDouble(txtprecioExamen.getText());
DecimalFormat numeroFormateado = new DecimalFormat("#.00");
dts.setPrecio(numeroFormateado.format(valor));

It will give you "0.99". You can add or subtract 0 on the right side to get more or fewer decimals.

Or use '#' to the right to make additional digits optional, as with #. ## (0.30) would drop the final 0 to become (0.3).

  

SO Source: How do I limit the number of decimals printed for a double?

Another way to specify the number of Decimals can be like this:

DecimalFormat formato = new DecimalFormat();
formato.setMaximumFractionDigits(2); //Con esta Linea.
String textoFormateado = formato.format(su_variable);

I hope it works for you :)

    
answered by 05.05.2018 / 15:15
source