Search code examples
c#floating-pointmedia-player

Converting int division to float (f)


I'm using MediaPlayer for playing sound, to change the volume you do have to set the value of a Volume property which is a float. (Example shows 0.5f as setting).

My settings for volume are percent based, how would I convert my say 80% volume to 0.5f to set the volume with. My code:

float volume = (Program.EffectsVolumeSlider.Percent > 0 ? Convert.ToSingle(Program.EffectsVolumeSlider.Percent / 100) : 0.0f);

this.FireballSound.Volume = volume;
this.IceSound.Volume = volume;
this.SmokeSound.Volume = volume;

This outputs the volume as 0.0 when the Program.EffectsVolumeSlider.Percent is 55?


Solution

  • Your code uses integer division:

    55 / 100 
    

    Will always return 0, because the integer piece of that division is 0. You need to cast one or more of the operands to float, the easiest way would be to do:

    Program.EffectsVolumeSlider.Percent / 100.0f
    

    This forces floating point division, which will return the correct value (.55)