-3

I've got a float value and i need to have only two decimals after comma. I'm using this code:

public static float getWhatINeed() {
  StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
  float total = 
      ((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
  return total;
}

And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:

String s = String.format("%.2f", 1.2975118);

somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
David_D
  • 1,404
  • 4
  • 31
  • 65
  • Seems duplilcate of http://stackoverflow.com/questions/8911356/whats-the-best-practice-to-round-a-float-to-2-decimals – Pankaj Kumar Nov 25 '13 at 10:55
  • Here [What's the best practice to round a float to 2 decimals?](http://stackoverflow.com/questions/8911356/whats-the-best-practice-to-round-a-float-to-2-decimals). – Simon Dorociak Nov 25 '13 at 10:56

4 Answers4

1

There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.

If you really NEED 2 decimals, use BigDecimal

You basically have 4 options:

  • return a float and deal with the fact that there are n decimal places
  • format to a String (which means a lot of string parsing if you need to do calculation)
  • convert to use BigDecimal
  • convert to use int and assume that the ones digit represents hundredths.
John B
  • 32,493
  • 6
  • 77
  • 98
0

Did you try:

new DecimalFormat("00.00").format(1.2975118);
Nermeen
  • 15,883
  • 5
  • 59
  • 72
0

You can try as follows

 DecimalFormat df = new DecimalFormat("0.##");
    float a=1.256f;
    System.out.println(df.format(a));
}

Out put

1.26
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
-3

After setting precision and get as a String You can canvert it back to float by

float f = Float.parseFloat(YourString);

Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
  • This will not work as it could result in a float equivelant to "1.120000000000000000001". This is why "This data type should never be used for precise values, such as currency" – John B Nov 25 '13 at 10:59