Rounding Decimas de Double keeping the tenths [duplicated]

1
tvTotalCommande.setText(String.valueOf(totalCommande)+"€");
    tvTotalRegler.setText(String.valueOf(totalDescuento+"€"));
    tvRemises.setText(String.valueOf((totalCommande-totalDescuento)+"€"));

In TotalCommande write me 5.5

In Remises write me 1.0999999996

In Total a Regler writes me 4.4

If the rest should give 1.1 But you are giving me the 1.0999999996

I need to get the result in 1.1 HELP!

    
asked by Eduardo Ricardez 25.04.2017 в 23:29
source

1 answer

1

I solved it like this:

One way of urgency to repair it and that has been perfect for all cases has been this:

 String prueba= String.valueOf(totalCommande);
    String prueba2=String.valueOf(totalDescuento);

    BigDecimal a = new BigDecimal(prueba);
    BigDecimal b = new BigDecimal(prueba2);

    a=a.setScale(2, RoundingMode.HALF_UP);
    b=b.setScale(2,RoundingMode.HALF_UP);


    tvTotalCommande.setText(String.valueOf(a)+"€");
    tvTotalRegler.setText(String.valueOf(b)+"€");

Pass the Doubles to String and from String to BigDecimal and the BigDecimal Round it using setScale with RoundingMode.HALF_UP. Because CEILING leaves it in 1.2, but HALF_UP leaves it in 1.1, being 2 decimals since it is already in the way of money, 1.10

    
answered by 26.04.2017 в 01:59