C# Convert ToByte(Single)

Description

Convert ToByte(Single) converts the value of the specified single-precision floating-point number to an equivalent 8-bit unsigned integer.

Syntax

Convert.ToByte(Single) has the following syntax.


public static byte ToByte(
  float value
)

Parameters

Convert.ToByte(Single) has the following parameters.

  • value - A single-precision floating-point number.

Returns

Convert.ToByte(Single) method returns 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.

Example

The following example converts a Single value to a Byte.


/* w w  w  . ja v a 2 s.  c  o m*/
using System;
public class MainClass{
  public static void Main(String[] argv){  
    byte byteVal = 0;
    float floatVal = 1.2F;
    
    // Byte to float conversion will not overflow.
    floatVal = System.Convert.ToSingle(byteVal);
    System.Console.WriteLine("The byte as a float is {0}.",
      floatVal);
    
    // Float to byte conversion can overflow. 
    try {
      byteVal = System.Convert.ToByte(floatVal);
      System.Console.WriteLine("The float as a byte is {0}.",
        byteVal);
    }
    catch (System.OverflowException) {
      System.Console.WriteLine(
        "The float value is too large for a byte.");
    }

  }
}
 

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version