Reputation: 820
i am trying simple calculation of float value but the output are not proper
Log.i("100/50", Float.toString(100/50));
Log.i("100/100", Float.toString(100/100));
Log.i("100/250", Float.toString(100/250));
Log.i("1/5", Float.toString(1/5));
logcat output
11-10 23:36:23.677: I/100/50(28562): 2.0
11-10 23:36:23.677: I/100/100(28562): 1.0
11-10 23:36:23.685: I/100/250(28562): 0.0
11-10 23:38:23.685: I/1/5(28562): 0.0
its a simple calculation of float, why its displaying such answer
Upvotes: 0
Views: 11875
Reputation: 53657
You are performing division of two integers. So by default output will be in integer. Instead of that try to type cast the dividend into float e.g. (float)100/250, so the output will be in float and you will get proper result.
E.g. instead of 100/250 try (float)100/250 or 100f/250.
Upvotes: 0
Reputation: 6925
Do like this
Log.i("100/250", Float.toString(100f/250f));
Log.i("1/5", Float.toString(1f/5f));
output is
11-11 12:25:32.198: I/100/250(351): 0.4
11-11 12:25:32.208: I/1/5(351): 0.2
Float.toString takes an input floating point
public static String toString (float f)
where f is the float to convert to a string.
More information is available on Developers Website.
Upvotes: 1
Reputation: 136022
You need to use floats instead of ints, try Log.i("100/50", Float.toString(100f/50));
this makes Java to use float arithmetic, otherwise it does int division then converts the result to float
Upvotes: 4
Reputation: 2850
Use this code.
Log.i("100/50", Float.toString(100/50f)); Log.i("100/100", Float.toString(100/100f)); Log.i("100/250", Float.toString(100/250f)); Log.i("1/5", Float.toString(1/5f));
Hope it will work for you.
Upvotes: 0