Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 414
Pramod Avatar asked Jun 25 '15 15:06

Pramod


People also ask

How do you convert an object to int or float in Python?

A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.

Which function is used to convert any data type to a floating-point number?

float(): This function is used to convert any data type to a floating-point number.

How do you change an object to float in pandas?

Use pandas DataFrame. astype() function to convert column from string/int to float, you can apply this on a specific column or on an entire DataFrame. To cast the data type to 54-bit signed float, you can use numpy. float64 , numpy.


1 Answers

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

like image 161
Jon Skeet Avatar answered Sep 29 '22 07:09

Jon Skeet