Mono Class Library: System.Convert Overview | Members

System.Convert.ToByte Method

Converts a float to a byte . [Edit]

public static byte ToByte (float value)

Parameters

value
The float value to be converted. [Edit]

Returns

value as a byte , rounded to the nearest integer. [Edit]

Exceptions

TypeReason
OverflowExceptionvalue is greater than byte.MaxValue or less than byte.MinValue, or value is equal to one of float.NaN, float.PositiveInfinity, or float.NegativeInfinity. [Edit]

Remarks

Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. [Edit]

Example

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
(float) 1.5 as byte = 2
(float) 2.5 as byte = 2
Exception occurred: System.OverflowException: Value was either too large or too small for an unsigned byte.
at Convert.ToByte(Int32 value)
at Convert.ToByte(Single value)
at ConvertByteTest.Main() in C:\ECMAExamples\ConvertToByte\ConvertFloat.cs:line 15

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0