Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to float by cast or Convert.ToSingle()?

In C# I can convert doubles to floats by a cast (float) or by Convert.ToSingle().

double x = 3.141592653589793238463; float a = (float)x; float b = Convert.ToSingle(x); 

a and b become equal.

Are there any differences between both techniques? Which one should I prefer and why?

like image 538
Seb Avatar asked Dec 04 '15 14:12

Seb


People also ask

How is double converted to float?

Using TypeCasting to Convert Double to Float in Java To define a float type, we must use the suffix f or F , whereas it is optional to use the suffix d or D for double. The default value of float is 0.0f , while the default value of double is 0.0d . By default, float numbers are treated as double in Java.

What is ToSingle in C#?

ToSingle(Object) Converts the value of the specified object to a single-precision floating-point number. ToSingle(Int32) Converts the value of the specified 32-bit signed integer to an equivalent single-precision floating-point number.

Can we convert double to float in C#?

In C# I can convert doubles to floats by a cast (float) or by Convert. ToSingle() . double x = 3.141592653589793238463; float a = (float)x; float b = Convert.

Can you cast a double to an int c#?

To convert a Double value to an integer value, use the Convert. ToInt32() method. Int32 represents a 32-bit signed integer.


1 Answers

From the .NET reference source:

public static float ToSingle(double value) {      return (float)value; } 

So, your answer is that they are exactly the same, under the hood.

Any preference between the two is strictly a personal style choice. Personally, I would always use the cast as it is shorter and and just seems more idiomatic to me.

like image 111
Glorin Oakenfoot Avatar answered Oct 05 '22 06:10

Glorin Oakenfoot