-5

I have this float 98.01645 and I'm getting 98.02 with this function:

    String lastCredit = String.format("%.2f", AppSingleton.getInstance().credit);

That I want is get 98.01 (only two decimals or not rounded number). I'm trying but I can't get the way to do it work.

halfer
  • 19,824
  • 17
  • 99
  • 186
S.P.
  • 2,274
  • 4
  • 26
  • 57

4 Answers4

3

Doing it manually:

String lastCredit = String.format("%.2f", java.lang.Math.floor(100.0*AppSingleton.getInstance().credit)*0.01);

Multiplying by 100.0 to move the decimal point two to the right, then rounding down, then moving the decimal point two to the left by multiplying with 0.01.

Adder
  • 5,708
  • 1
  • 28
  • 56
1

You can try this

    String lastCredit = String.format("%.2f",Math.floor((98.01645 * 100)) / 100);
    System.out.println(lastCredit);

You basically multiply the value by 100 because you need 2 numbers after the decimal and round down that value. After you have the result you divide it by 100 again.

Rvdrichard
  • 335
  • 3
  • 12
0

Use below code instead of String lastCredit = String.format("%.2f", AppSingleton.getInstance().credit);

    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    String lastCredit = decimalFormat.format(f);
Archana
  • 597
  • 4
  • 18
0

I would not call this elegant, but you can just use String.format to get 3 decimal places and remove the last using substring:

String lastCredit = String.format("%.3f", AppSingleton.getInstance().credit);
lastCredit = lastCredit.substring(0, lastCredit.length() - 1);
eike
  • 1,314
  • 7
  • 18
  • This assumes that "%.2f" gives you trailing zeros, which I cannot test, because I am on mobile right now. – eike Mar 09 '18 at 12:19