Java - Round a float and place it in a jTextField

1

I have a project in Netbeans based on MVC. In the part of the "ABMProduct" view, I have the following code:

private void txtGananciaActionPerformed(java.awt.event.ActionEvent evt) {                                            
    float pv = 0, pc = 0, pg;
    pc = Float.parseFloat(txtPrecioCompra.getText());
    pg = (pc * Float.parseFloat(txtGanancia.getText())) / 100;
    pv = pc + pg;

    txtPrecioVenta.setText(String.valueOf(pv));
}

Basically what it does is: I give it a purchase price, I give it a profit and based on that, it calculates the sale price.

What I want to do is that the sale price is rounded to a maximum of 0.00

What can I do? Thanks!

    
asked by Carlos A. Vivas 16.03.2017 в 15:13
source

1 answer

0

Since you want it to display as String:

String.format("%.2f", pv)

So you format it as a float of two decimals

And in your code:

txtPrecioVenta.setText(String.format("%.2f", pv));

To return a number with points and not commas, you have to indicate the Locale we want (for example, Locale.US would be valid):

txtPrecioVenta.setText(String.format(Locale.US, "%.2f", pv));

If you wanted to round the value to then use in arithmetic operations the correct thing would be to use a BigDecimal object.

    
answered by 16.03.2017 / 15:16
source