Converts a decimal to a byte .
- value
- The decimal 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.
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.Note: This process is known as banker's rounding.
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
(decimal) 1.5 as byte = 2
(decimal) 2.5 as byte = 2
Exception occurred: System.OverflowException: Value was either too large or too small for an unsigned byte.
at System.Decimal.ToByte(Decimal value)
at Convert.ToByte(Decimal value)
at ConvertByteTest.Main() in C:\ECMAExamples\ConvertToByte\ConvertDecimal.cs:line 15
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0