Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a (generic) number type is an integral or nonintegral type in C#?

Tags:

c#

math

generics

I've got a generic type T. Using Marc's Operator class I can perform calculations on it.

Is it possible to detect by mere calculations whether the type is an integral or a nonintegral type?

Perhaps there is a better solution? I'd prefer to support any possible type, so I'd like to prevent hard-coding which types are integral/nonintegral.

Background info

The situation I find myself in is I want to cast a double to T but round to the nearest value of T to the double value.

int a = (int)2.6 results in 2 while I want it to result it in 3, without knowing the type (in this case int). It could also be double, in which case I want the outcome to be 2.6.

like image 936
Steven Jeuris Avatar asked Dec 15 '11 13:12

Steven Jeuris


1 Answers

Have you tried Convert.ChangeType? Something like:

Convert.ChangeType(1.9d, typeof (T))

It will work for all numeric types I think (as long as the first parameter is iConvertible and the type is a supported one which all basic numerics should be I believe).

Its important to mention that this will call something like double.ToInt32 which rounds values rather than truncates (bankers rounding I believe).

I tested this in a little LinqPad program and it does what I think you want:

void Main()
{
    var foo = RetNum<decimal>();
    foo.Dump();
}

public static T RetNum<T>()
{
    return (T)Convert.ChangeType(1.9d, typeof (T));
}
like image 199
Chris Avatar answered Oct 14 '22 16:10

Chris