开发者

how to get a float from int

开发者 https://www.devze.com 2023-01-20 08:40 出处:网络
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 ...

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


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);


f/Math.pow(10,Integer.toString(f).length());

Find the length of the Integer by first converting it to String and using the String length() method.

  • There probably are more clever ways of doing it.

___EDIT____

f/Math.pow(10,Math.ceil(Math.log10(Math.abs(f)+1)));

Handles negatives(and uses log).


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


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

float f = .1234f;  // Note the trailing f
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号