Question:
I am doing small problems as a practice for the course I am following in Java.
I want when I enter two results, like for example:
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 is complete.
Thanks
CODE
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);
}
}
Answer:
The value internally is the same, you're just trying to represent it, that's why I recommend using
String.format(java.util.Locale.US,"%.3f", cambio);
The first argument is the locale that will let you know if points or commas are used in decimals, the second is a format string telling it that it will receive a floating point number ( %f
) but that it will to always format with three decimal places %.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));
Greetings.