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.
The following example converts a byte value to a decimal and a decimal value to a byte.
code reference: System.Convert Snippets#18
The following example demonstrates converting decimal values to byte values.
C# Example
using System; class ConvertByteTest { static public void Main() { decimal decimal0 = 0.0m; decimal decimal1 = 1.5m; decimal decimal2 = 2.5m; decimal decimal3 = -1.0m; byte byte0 = Convert.ToByte(decimal0); byte byte1 = Convert.ToByte(decimal1); byte byte2 = Convert.ToByte(decimal2); Console.WriteLine("(decimal) {0} as byte = {1}",decimal0,byte0); Console.WriteLine("(decimal) {0} as byte = {1}",decimal1,byte1); Console.WriteLine("(decimal) {0} as byte = {1}",decimal2,byte2); byte byte3 = Convert.ToByte(decimal3); //Throws an exception. Console.WriteLine("(decimal) {0} as byte = {1}",decimal3,byte3); } }
The output is
(decimal) 0 as byte = 0