How to convert object type into float where object can be any type of number like int, long, float, double etc

13,267

I believe Convert.ToSingle will be able to handle any "core" numeric type you throw at it.

Share:
13,267
Pramod
Author by

Pramod

Updated on June 04, 2022

Comments

  • Pramod
    Pramod almost 2 years

    I am having as stream of objects, which can be either type of number like int, short, long, float etc... What is the best way to convert it into a number. Best way could be something ToNumber(object oNumber)

    // Best magic could be
    var number = (somemagic) oNumber;
    
    float operator1 = oNumber is int 
      ? (float)(int)oNumber
      : oNumber is long 
         ? (float)(long)oNumber
         : oNumber is float 
            ? (float)oNumber 
            : (float)(int)oNumber;
    

    assuming float will be able to take all number expect double

  • Pramod
    Pramod almost 9 years
    What if my object is float, will I loose precision due to single level precision conversion?
  • Jon Skeet
    Jon Skeet almost 9 years
    @user2685250: What do you mean? If it's already a float, then a conversion to float shouldn't lose any precision, no. (There are some subtleties here around intermediate values being handled at higher precision, but fundamentally that won't matter if you want the value with 32-bits of precision...)
  • Pramod
    Pramod almost 9 years
    Thanks Jon for confirmation. Essentially I am parsing an postfix expression which can have any number like float, double, int, short, uint, long etc..