double -> float : casting or Convert.ToSingle ?
-
Hi, I want to convert variables of type double to type float in my C# app. I've read that casting from a double to float results in the double being rounded to the nearest float value. That is exactly what I need (as opposed to truncation). However, I've also seen that the Convert.ToSingle(double) method uses rounding as well to convert the double to a float. Is there any difference between these two techniques - casting and ToSingle? Are there scenarios in which one is preferable over the other? What about overhead? Thanks!
-
Hi, I want to convert variables of type double to type float in my C# app. I've read that casting from a double to float results in the double being rounded to the nearest float value. That is exactly what I need (as opposed to truncation). However, I've also seen that the Convert.ToSingle(double) method uses rounding as well to convert the double to a float. Is there any difference between these two techniques - casting and ToSingle? Are there scenarios in which one is preferable over the other? What about overhead? Thanks!
I don't know technical point of this but from my personal expirience I ecourage everyone to use Convert.To... over casting because several times it happened to me that (casting) produced error and on contratry Convert.To... never made any trouble.
-
Hi, I want to convert variables of type double to type float in my C# app. I've read that casting from a double to float results in the double being rounded to the nearest float value. That is exactly what I need (as opposed to truncation). However, I've also seen that the Convert.ToSingle(double) method uses rounding as well to convert the double to a float. Is there any difference between these two techniques - casting and ToSingle? Are there scenarios in which one is preferable over the other? What about overhead? Thanks!
crushinghellhammer wrote: Is there any difference between these two techniques - casting and ToSingle? The basic difference is that a cast can thrown an exception which means anytime you cast something you should also wrap it in a try/catch block to handle any exception that is thrown. This in turn emits additional IL instructions, not much but it's there. - Nick Parker
My Blog | My Articles