Float to string conversion - how to display two or more decimal places?

1

I have the following code, which returns values of type float . How can I make the result appear with 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));
    
asked by anonymous 17.02.2018 / 17:15

1 answer

0

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 you want, simply pass the value in place of 2 by parameter as well.

Then, to use it:

rsDivisao.setText(toBigDecimal(divisao).toString());
    
17.02.2018 / 18:11