Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified cast is not valid.. how to resolve this

Tags:

c#

I have the below function

public object Convert(object value)  {     string retVal = string.Empty;     int oneMillion = 1000000;     retVal = ((double)value / oneMillion).ToString("###,###,###.###");     return retVal;  } 

I am invoking like

var result  = Convert(107284403940); 

Error: "Specified cast is not valid."

how to fix...

Note:~ the object value can be double, decimal, float, integer(32 and 64)..anything

Is it possible to do the typecasting at runtime?

like image 535
learner Avatar asked Apr 07 '11 07:04

learner


2 Answers

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

like image 101
Kieren Johnstone Avatar answered Sep 20 '22 18:09

Kieren Johnstone


If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

like image 42
Sanjeevakumar Hiremath Avatar answered Sep 18 '22 18:09

Sanjeevakumar Hiremath