C# 中的 Decimal.ToInt16() 方法


C# 中的 Decimal.ToInt16() 方法用于将指定 Decimal 的值转换成等效的 16 位有符号整数。

语法

语法如下 −

public static short ToInt16 (decimal val);

以上,Val 是要转换的小数。

示例

下面我们来看一个实现 Decimal.ToInt16() 方法的示例 −

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = -3.578m;
      Decimal val2 = 9.352m;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      short res1 = Decimal.ToInt16(val1);
      short res2 = Decimal.ToInt16(val2);
      Console.WriteLine("16-bit signed integer (value1) (Decimal to signed integer) = "+res1);
      Console.WriteLine("16-bit signed integer (value1) (Decimal to signed integer) = "+res2);
   }
}

输出

将输出以下内容 −

Decimal 1 = -3.578
Decimal 2 = 9.352
16-bit signed integer (value1) (Decimal to signed integer) = -3
16-bit signed integer (value1) (Decimal to signed integer) = 9

示例

下面我们来看另一个实现 Decimal.ToInt16() 方法的示例 −

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 0.001m;
      Decimal val2 = 1.000m;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      short res1 = Decimal.ToInt16(val1);
      short res2 = Decimal.ToInt16(val2);
      Console.WriteLine("16-bit signed integer (value1) (Decimal to signed integer) = "+res1);
      Console.WriteLine("16-bit signed integer (value1) (Decimal to signed integer) = "+res2);
   }
}

输出

将输出以下内容 −

Decimal 1 = 0.001
Decimal 2 = 1.000
16-bit signed integer (value1) (Decimal to signed integer) = 0
16-bit signed integer (value1) (Decimal to signed integer) = 1

更新于: 2019-11-12

53 次浏览量

启动您的事业

完成课程获得认证

开始学习
广告