i want throw exception if value of decimal is bigger than float (without floating point)
this sample code below works fine (throw overflowException) for integer
decimal a = decimal.MaxValue;
int b = checked(int.Parse(a.ToString()));
but this sample code does not throw any exception
decimal a = decimal.MaxValue;
float b = checked(float.Parse(a.ToString())); // b is 7.92281625E+28
how find out if value of decimal is bigger than float(without floating point)?
int b = checked(int.Parse(a.ToString()));
is a very bad way of checking whether a value will cause an OverflowException
, because you don't know how a
will be represented as a string.
Instead, use a cast :
decimal d = decimal.MaxValue;
int i = (int)d;
// Throws OverflowException
As @Enigmativity and @CodeCaster pointed out in the comments, the integer part of a decimal
will always fit in a float
:
decimal d = decimal.MaxValue;
float i = (float)d;
// No problem!
You can use decimal.Truncate if you just need to remove the fractional part of a decimal
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.