Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not 100% sure what you're asking, but:</p> <p>To check if it's an integral <strong>type</strong>, use this: <code>if (obj is float || obj is double)</code>, or <code>if typeof(T) == typeof(float) || typeof(T) == typeof(double))</code></p> <p>To check if it's an integral <strong>value</strong>, cast it to a double, and then do <code>if(value == Math.Round(value))</code></p> <p>Of course, that is assuming that you have a number in the first place. I believe that the Operator class you're using supports things like DateTime. Would it be better to make your generic method have a generic constraint <a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" rel="nofollow"><code>where T : IConvertible</code></a>? That way there'd be explicit <code>ToDouble</code> and <code>ToInteger</code> methods.</p> <p><strong>Edit</strong>:</p> <p>I think I understand: you've got two local variables, <code>double d; T num;</code>. You want to cast <code>d</code> to type <code>T</code>, but with proper rounding if <code>T</code> is a integral type. Is that correct?</p> <p>Assuming that's correct, here's what I'd do:</p> <pre><code>public void SomeMethod&lt;T&gt;() { double d; // I think I got all the floating-point types. There's only a few, so we can test for them explicitly. if(typeof(T) != typeof(double) &amp;&amp; typeof(T) != typeof(float) &amp;&amp; typeof(T) != typeof(Decimal)) { d = Math.Round(d); } T converted = Convert.ChangeType(d, typeof(T)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload