# Tutorial :how to get output of a variable as float value

### Question:

i m having the follwing problem.. want to get the result in float

suppose

``int a= convert.toint32(textbox1.text);  int b= convert.toint32(textbox2.text);    float ans= math.sqrt(a*b);  label1.text= ans.tostring();  ``

output..

``a=7  b=3  ``

ans should be= 4.582 but i get an error

cannot implicitly convert type 'double' to 'float'.

pls help..how can i get the float ans...

### Solution:1

``double ans = math.sqrt(a*b);  ``

### Solution:2

double is just a larger float. Math.Sqrt() returns a double, not a float. You can fit more numbers in a double than the float type can accurately represent, and so in your code the compiler can't promise that an automatic conversion won't not lose important data, hence the exception.

To get around this, you have two options:

1. explicit cast: `float ans = (float)Math.Sqrt(a*b);`
2. use a double: `double ans = Math.Sqrt(a*b);`

Of the two, I recommend the latter.

As a side note, the reverse conversion is okay because double can always accurately represent anything you might find in a float variable. For example, this is perfect okay from the type system's point of view:

``float divide(int a, int b) { return a/(float)b;}  double ans = divide(5,2);  ``

### Solution:3

Math.sqrts return value is double. So, you have two options.

1. Convert the returned double to a float as so: `float ans = (float)Math.sqrt(a * b);`
2. Change the type of ans to double: `double ans = Math.sqrt(a * b);`

Option 2 would, in most cases, be your best option unless you specifically need a float, because double is a higher precision value.

### Solution:4

You could just cast directly to a float.

`` float ans = (float)Math.Sqrt( a * b );  ``

### Solution:5

You need to explicitly cast the result as `double` has a greater range of values than a `float` (16 digits to 7):

``  float ans= (float)Math.Sqrt(a*b);  ``

But unless you have a reason you haven't told us about then just use a `double`.

### Solution:6

``float ans= math.sqrt(a*b);   ``

should be

``float ans= (float)Math.Sqrt(a*b);   ``

You need to explicitly cast to `float` because this conversion results in loss of information so the compiler will not automatically cast for you. That way the compiler ensures that the lossy conversion is intentional.

### Solution:7

`Math.Sqrt` method returns a value of type `double`.

But you're trying to put this value to `float` type. But `double` doesn't have an implicit conversion to `float`. So the alternatives:

• declare an answer as `double`: `double ans = Math.Sqrt(a*b)`

• or explicitly convert result to `float` type: `(float)Math.Sqrt(a*b)`.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »