- value
- The double value to be converted.
value as a byte , rounded to the nearest integer.
Type Reason OverflowException value is greater than byte.MaxValue or less than byte.MinValue, or value is equal to one of double.NaN, double.PositiveInfinity, or double.NegativeInfinity.
Prior to the conversion, if value is halfway between two numbers, it is rounded to the number that has an even digit in the rightmost decimal position. For example, when rounded to two decimals, the value 2.345 becomes 2.34 and the value 2.355 becomes 2.36
The following example demonstrates converting double values to byte values.
C# Example
using System; class ConvertByteTest { static public void Main() { double double0 = 0.0; double double1 = 1.5; double double2 = 2.5; double double3 = -1.0; byte byte0 = Convert.ToByte(double0); byte byte1 = Convert.ToByte(double1); byte byte2 = Convert.ToByte(double2); Console.WriteLine("(double) {0} as byte = {1}",double0,byte0); Console.WriteLine("(double) {0} as byte = {1}",double1,byte1); Console.WriteLine("(double) {0} as byte = {1}",double2,byte2); byte byte3 = Convert.ToByte(double3); //Throws an exception. Console.WriteLine("(double) {0} as byte = {1}",double3,byte3); } }The output is
(double) 0 as byte = 0
(double) 1.5 as byte = 2
(double) 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(Double value)
at ConvertByteTest.Main() in C:\ECMAExamples\ConvertToByte\ConvertDouble.cs:line 15
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0