Henriquez10 Asked: 2020-05-06 01:55:04 +0800 CST 2020-05-06 01:55:04 +0800 CST 2020-05-06 01:55:04 +0800 CST Limit the number of decimals 772 If I want to enter the price $6.00, how do I limit the number of decimals? Wearing: dts.setPrecio(Double.parseDouble(txtprecioExamen.getText())); java 1 Answers Voted Best Answer J. Rodríguez 2020-05-06T05:15:41+08:002020-05-06T05:15:41+08:00 Use a DecimalFormatter : double numero = 0.9999999999999; DecimalFormat numeroFormateado = new DecimalFormat("#.00"); System.out.println(numeroFormateado.format(numero)); So 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 hand side to get more or less decimal places. Or use '#'right to make the extra digits optional, as with #. ##(0.30) you would drop the trailing 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 helps you :)
Use a DecimalFormatter :
So based on your code it would be something like this:
It will give you "0.99". You can add or subtract 0 on the right hand side to get more or less decimal places.
Or use
'#'
right to make the extra digits optional, as with#. ##
(0.30) you would drop the trailing 0 to become (0.3).Another way to specify the number of Decimals can be like this:
I hope it helps you :)