I noticed in another post, someone had done something like:
double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
Why did they use the convert function, rather than:
double d = 3.1415;
int i = (int)d;
which has an implicit floor and convert.
Also, more concerning, I noticed in some production code I was reading:
double d = 3.1415;
float f = Convert.ToSingle(d);
Is that the same as:
float f = (float)d;
Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
The difference is this: Int32. Parse() and Int32. TryParse() can only convert strings.
Thus int32 would be limited to a value between (-256^4/2) and (256^4/2-1). And int64 would be limited to a value between (-256^8/2) and (256^8/2-1).
ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.
Casting to int is implicit truncation, not implicit flooring:
double d = -3.14;
int i = (int)d;
// i == -3
I choose Math.Floor or Math.Round to make my intentions more explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With