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
  • 37,241
  • 25
  • 195
  • 267
vijayk
  • 2,633
  • 14
  • 38
  • 59
  • 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
  • 40,646
  • 13
  • 77
  • 103
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,092
  • 22
  • 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
  • 158,255
  • 15
  • 216
  • 276
-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,729
  • 10
  • 59
  • 55