Converts the value of the specified single-precision floating-point number to an equivalent 8-bit unsigned integer.
value, rounded to the nearest 8-bit unsigned integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
Type Reason OverflowException value is greater than byte.MaxValue or less than byte.MinValue, or value is equal to one of float.NaN, float.PositiveInfinity, or float.NegativeInfinity.
The following example demonstrates converting float values to byte values.
C# Example
using System; class ConvertByteTest { static public void Main() { float float0 = 0.0f; float float1 = 1.5f; float float2 = 2.5f; float float3 = -1.0f; byte byte0 = Convert.ToByte(float0); byte byte1 = Convert.ToByte(float1); byte byte2 = Convert.ToByte(float2); Console.WriteLine("(float) {0} as byte = {1}",float0,byte0); Console.WriteLine("(float) {0} as byte = {1}",float1,byte1); Console.WriteLine("(float) {0} as byte = {1}",float2,byte2); byte byte3 = Convert.ToByte(float3); //Throws an exception. Console.WriteLine("(float) {0} as byte = {1}",float3,byte3); } }
The output is
(float) 0 as byte = 0