【问题标题】:how throw exception if decimal value is bigger than float in C#如果十进制值大于C#中的浮点数,如何抛出异常
【发布时间】:2017-08-26 13:50:58
【问题描述】:

如果十进制值大于浮点数(没有浮点数),我想抛出异常

下面的示例代码对整数工作正常(抛出溢出异常)

decimal a = decimal.MaxValue;
int b = checked(int.Parse(a.ToString()));

但是这个示例代码没有抛出任何异常

decimal a = decimal.MaxValue;
float b = checked(float.Parse(a.ToString())); // b is 7.92281625E+28

如何判断小数的值是否大于浮点数(没有浮点数)?

【问题讨论】:

  • 小数的整数部分总是适合浮点数。
  • find out if value of decimal is bigger than float(without floating point) 是什么意思?你想把小数点后的所有东西都扔掉,然后比较整数部分吗?
  • float 的最大值为 3.402823E+38。小数的最大值为79228162514264337593543950335decimal 不能大于 float

标签: c#


【解决方案1】:
int b = checked(int.Parse(a.ToString()));

检查一个值是否会导致OverflowException 是一种非常糟糕的方法,因为您不知道a 将如何表示为字符串。

改为使用cast:

decimal d = decimal.MaxValue;

int i = (int)d;
// Throws OverflowException

正如 @Enigmativity 和 @CodeCaster 在 cmets 中指出的那样,decimal 的整数部分总是适合 float

decimal d = decimal.MaxValue;

float i = (float)d;
// No problem!

如果您只需要删除decimal 的小数部分,您可以使用decimal.Truncate

【讨论】:

  • 他想要float。此代码不会与 float 一起抛出。
  • 非常感谢您知道关于问题第二部分的任何想法吗?我是 C# 新手
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 2021-05-04
  • 2011-07-25
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
相关资源
最近更新 更多