tags:

views:

175

answers:

4

i has a int:

int f=1234;//or f=23 f=456 ...

i want to get:

float result=0.1234; // or 0.23 0.456 ...

dont useing:

float result = parseFloat ("0."+f);

what's best way to do?

thanks

+9  A: 

How about?

float result = f/1000.0f;

More generally, if you need to size the integer for various values of f you can do something like this:

int divisor;
for(divisor = 1; f / divisor > 0; divisor *= 10);
float result = (float)f/(float)divisor;

Or more concisely with logarithms:

float result = f / Math.pow(10, Math.floor(Math.log10(f))+1);
Mark E
thanks, i writed comment, f maybe to f=23 f=456 ,i dont know f's length
Zenofo
Needs moar log, christ don't they teach math in high school anymore?
BlueRaja - Danny Pflughoeft
sorry for my stupid question, this solution (f/f.length*10) run speed better to parseFloat("0."+f) ?
Zenofo
@Zenofo: I'm sure the differences are negligible, do what makes sense to you or is the most readable...i.e. do the most maintainable thing.
Mark E
Did you test `float result = f / Math.pow(10,Math.floor(Math.log10(f)));` because it fails for `1234`? Off by one?
Ishtar
`float result = (float) (f / Math.pow(10, Math.floor(Math.log10(f)+1)));` but i think `parseFloat ("0."+f);` is better, thanks
Zenofo
+2  A: 
kasgoku
Needs moar log.
BlueRaja - Danny Pflughoeft
f/Math.pow(10,Math.ceil(Math.log10(Math.abs(f)+1))); \\ Uses log and handles negative numbers
kasgoku
A: 

I think he means, "how do I specify a literal float?"

float f = .1234f;  // Note the trailing f
Tony Ennis
+1  A: 

I think your solution works better than most suggested answers... Changed it a bit to cover negative numbers as well.

int f=1234;
if (f<0)
    result = -1.0f*parseFloat ("0."+(-f));
else
    result = parseFloat ("0."+f);

Still fails at Integer.MIN_VALUE though and note the loss in precision. For example:

int f=2147483647; //gives 
result == 0.21474837f
Ishtar