Conversion of float to string - how to display two or more decimal places?

Asked

Viewed 300 times

1

I have the code below, which returns values of type float. How can I get the result presented to two or more decimal places?

private void btnDividirActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:

        float n1 = Float.parseFloat(txtNumerador.getText());
        float n2 = Float.parseFloat(txtDenominador.getText());

        float divisao = n1 / n2;
        float resto = n1 % n2;

        rsDivisao.setText(Float.toString(divisao));
        rsResto.setText(Float.toString(resto));
  • But it’s supposed to present with two decimal places even if they’re zeroes ?

1 answer

1

You can use this method:

public BigDecimal toBigDecimal(float number) {
    BigDecimal bd = new BigDecimal(Float.toString(number)); // converte para BigDecimal
    bd.setScale(2, BigDecimal.ROUND_HALF_UP); // arredonda para 2 casa decimais o valor
    return bd;
}

If you want to change the number of decimal places desired, just pass the value instead of the 2.

So to use it:

rsDivisao.setText(toBigDecimal(divisao).toString());
  • Thanks for the help.

  • @Rogeriosantos for nothing. If the answer helped you, could you mark the solution as correct? Thank you

  • the method worked well, but the call shows error ( incompatible types: Bigdecimal cannot be converted to String).

  • I was able to solve as follows: rsDivisao.setText(String.format("%. 2f", division)); rsResto.setText(String.format("%. 2f", rest));

  • 1

    @Rogeriosantos, call the method toString() Bigdecimal to work. A warning: see if you really need to use float for your problem. If you want to work accurately in decimal places, the BigDecimal Java is more recommended, because with float (or double) you will soon notice problems in precision.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.