Here in this condition my 'f' value always will be from 88 to 108 and I need to map that value to my seekbar range that is from 0 to 200
My expression presented here is working very fine with all values other than if f=88.1,88.2,89.1;89.2....and so on
String value = b.getText().toString();
float f= Float.parseFloat(value);
int progress = (int) (f-(float)88.0)*10;
s.setProgress( progress);
And I set my progress in seek bar and I get back my value of f like this and is set a text view
float channel = (float) ((float)88.0 + ((float)progress/10));
String mytext=Float.toString(channel);
t.setText(mytext);
But textview shows 0.1 less than my original value; like shows f=88.1 for 88.2, f=88.0 for 88.1 and so on...
Can anybody help me to solve this?
i got the solution and i marked it as correct, but can anybody tell me why that strange thing was happening ?
Binary floating-point does not represent all values exactly. In particular, the values 88.1, 88.2, 89.1, and 89.2 are not representable in binary floating-point. Instead, any calculation or conversion whose exact mathematical result would be one of those values produces instead a binary floating-point value that is close to the exact result.
In the usual default modes, the representable result closest to the exact result is returned. (This is for each operation performed. When you have multiple arithmetic operations, the effects of rounding to representable results may compound, producing greater differences.) Sometimes the representable result is greater than the exact result, sometimes it is less.
Therefore, your object f
does not contain 88.1, 88.2, 89.1, or 89.2. It contains some other value that is slightly higher or slightly lower. When you subtract 88 and multiply by ten, you might have exactly 1 or 2, if the effects of rounding happen to have canceled and given you an exact result, but you might have a value that is slightly higher than 1 or 2 or a value that is slightly lower than 1 or 2.
Then you convert that value to an integer using an (int)
cast. This conversion truncates; it does not round. So, if the value is slightly lower than 1, the result of the cast is 0.
If you want the conversion to integer to round instead of truncating, then you can add .5: int progress = (int) ((f-88.f)*10 + .5);
. (If you care about rounding direction in case of a tie, when the distances to the nearest integers are exactly equal, you must use a different solution.)
This rounding will alleviate the particular problem you ask about in this question, but artifacts may still occur. For example, if f is very near some value like 88.15, then rounding it to produce a progress of 1 (for .1) or 2 (for .2) and then reconstructing f from that progress may produce 88.2 even though f is slightly closer to 88.1 (slightly under 88.15) or may produce 88.1 even though f is slightly closer to 88.2 (slightly over 88.15).