Problem with decimals in Java


I'm doing small problems like practice for the course I'm following from Java.

I want when I enter two results, such as:

50,000 and 20,000 the result you get is 30,000 and not 30.0

On the contrary when I write 50,000 and 42,521 the result if it is complete



import javax.swing.JOptionPane;

public class Supermercado {

    public static void main (String [] args) {

        String pago = JOptionPane.showInputDialog("Ingrese el monto pagado por el cliente");

        double pago2 = Double.parseDouble(pago);

        String precio = JOptionPane.showInputDialog("Ingrese el valor del producto");

        double precio2 = Double.parseDouble(precio);

        double cambio = pago2 - precio2;

        JOptionPane.showMessageDialog(null,"El cambio es igual a " + cambio);

asked by Daymox 19.12.2018 в 00:10

2 answers


The value is internally the same, you're just trying to represent it, that's why I recommend you use

String.format(java.util.Locale.US,"%.3f", cambio);

The first argument is the local configuration that will let you know if you use periods or commas in decimals, the second is a format string in which it tells you that you will receive a number with floating point ( %f ) but it will always be formatted with three decimals %.3f .

That method returns a string with the format already applied.

JOptionPane.showMessageDialog(null,"El cambio es igual a " + String.format(java.util.Locale.US,"%.3f", cambio));


answered by 19.12.2018 / 00:15

Well, use the following line:

NumberFormat formatter = new DecimalFormat("#0.000");     

You can use the NumberFormat and DecimalFormat class to format the result you want to print, you propose the number of zeros after the decimal point. In the example above, when I run it, it prints:

answered by 19.12.2018 в 00:20