Reputation: 11652
I'm using a library where I need to set a value on a variable and it only accepts float
type, but the TrackBar
Control only accepts Int32
for its Value
property.
So let's say that the Min value of TrackBar
is 0 and Max value is 100. And the Current value of TrackBar
is 67; how do I convert that value to its equivalent in float? So it should become something like 0.067, if I'm correct.
Upvotes: 0
Views: 196
Reputation: 3255
To convert int
to float just cast:
(float)trackBar.Value;
or
Convert.ToSingle(trackBar.Value);
Note that if you need to change range you need to perform at least division. I.e. in your case it looks like value is percentage, so divide by 100.0:
trackBar.Value / 100.0f;
Note that if you use 100
than result will be wrong as using integer division ( trackBar.Value / 100
will always be 0
).
In general conversion for integer in 0-n
range to (mixValue, maxValue)
range:
(trackBar.Value /( (float) maxValue - minValue)) + minValue;
Upvotes: 2
Reputation: 1659
Divide the integer value by 100 as a float
to get the percentage as a float
. This will cause the value to be normalized to fall between 0 and 1 as a decimal value:
float trackBarPercentage = trackBar.Value / 100f;
Dividing the integer
value by a float
value will cause the right-hand side to automatically be casted to the float
type. See the MSDN article Casting and Type Conversions for more info.
Upvotes: 2