0

I have Float value like 0.152545 I just want 0.1f.
How this is possible..
By using String I was get the String value.The following code show the result.

 String pass = pass.substring(0, Math.min(pass.length(), 3));
 pass=pass+"f";

This gives me String value like0.1f ,But I want only Float value like 0.1f.

Cœur
  • 34,719
  • 24
  • 185
  • 251
vijayk
  • 2,533
  • 10
  • 33
  • 56
  • 1
    Why don't you convert it to a float and set the precision you want? – Maroun Jun 18 '13 at 13:05
  • 1
    Just a remark on usage: one tenth, 0.1, has no exact representation in bits, and the float is just an approximation (sum using 1/32, 1/64, 1/128, ...). So 1000 * 0.1 will not be 100.0. – Joop Eggen Jun 18 '13 at 13:15

4 Answers4

6

It would be appropriate place where you should use DecimalFormat, And .#f would be pattern for your case.

Find more on Number formatting in java.

Some related question -

Community
  • 1
  • 1
Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101
0

You could use a BigDecimal.

float f = 0.152545f;
BigDecimal bd = new BigDecimal(f);
bd = bd.setScale(1, RoundingMode.DOWN);
f = bd.floatValue();

Works fine even if you have a float stored as a String.

String floatAsString = "0.152545";
BigDecimal bd = new BigDecimal(floatAsString);
bd = bd.setScale(1, RoundingMode.DOWN);
float f = bd.floatValue();
raupach
  • 3,062
  • 23
  • 30
0

You could do:

DecimalFormat format = new DecimalFormat("0.0");
format.setRoundingMode(RoundingMode.DOWN);
format.setMaximumFractionDigits(1);
System.out.println(format.format(0.152545) + "f");
Reimeus
  • 155,977
  • 14
  • 207
  • 269
-1

How about

float new = Math.round( 10.0 * f ) / 10.0;

It won't be precise, as floats/doubles are just sums of finite series of 1/2^n, but might be good enough for you.

Perhaps you should be thinking about presenting the float with one significant decimal point and keep full precision internally?

Cheers,

Anders R. Bystrup
  • 15,324
  • 10
  • 61
  • 54