當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Decimal.ToByte()用法及代碼示例


此方法用於將指定的Decimal的值轉換為等效的8位無符號整數。

用法: public static byte ToByte (decimal a);

參數:
a:此參數指定要取反的小數。


返回值:將返回一個與a相等的8位無符號整數。

異常:如果值即a小於MinValue或大於MaxValue,則此方法將給出OverflowException。

以下示例程序旨在說明Decimal.ToByte(Decimal)方法的用法:

示例1:

// C# program to demonstrate the 
// Decimal.ToByte(Decimal) Method 
using System; 
using System.Globalization; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal variable 
            Decimal a = 127.97m; 
  
            // using ToByte() method; 
            byte value = Decimal.ToByte(a); 
  
            // Display the byte value 
            Console.WriteLine("The Byte value "+ 
                             "is : {0}", value); 
        } 
  
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
The Byte value is : 127

示例2:

// C# program to demonstrate the 
// Decimal.ToByte(Decimal) Method 
using System; 
using System.Globalization; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal variable 
            Decimal a = -0.999m; 
  
            // using ToByte() method; 
            byte value = Decimal.ToByte(a); 
  
            // Display the byte value 
            Console.WriteLine("The Byte value"+ 
                           " is : {0}", value); 
        } 
  
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
The Byte value is : 0

示例3:溢出異常程序

// C# program to demonstrate the 
// Decimal.ToByte(Decimal) Method 
using System; 
using System.Globalization; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal variable 
            Decimal a = -98.45m; 
  
            // using ToByte() method; 
            byte value = Decimal.ToByte(a); 
  
            // Display the byte value 
            Console.WriteLine("The Byte value "+ 
                             "is : {0}", value); 
        } 
  
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Exception Thrown: System.OverflowException

參考:



相關用法


注:本文由純淨天空篩選整理自IshwarGupta大神的英文原創作品 Decimal.ToByte() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。