What is the academic route for converting C# number types from one to another?
Based on my tests, casting a decimal or double to an int or long simply keeps the whole number portion of the number and discards the decimal portion. Reversely, you can have an int variable and assign it directly to a decimal variable with开发者_如何学Goout casting and it will perform an implicit conversion.
It works, but just because it works doesn't always mean it's the best way. Are there any performance implications over this type of conversion or is it best to use Convert.ToWhatever()?
Convert.ToWhatever() is likely going to be less performant. The real point is, that whatever performance implications you might have are going to be so miniscule that it's an edge case. If number conversions are a performance problem, there's likely another solution that's going to be more helpful and a better use of your time / money.
You require the cast for decimal to int or double to int because the conversion results in a loss of precision, therefore rather than allowing you to inadvertently perform a lossy operation you are expected to be explicit about it.
Going the other way around, a double or decimal can fully represent any value assigned from an int and therefore the conversion can be done implicitly on your behalf.
The only question is, is the cast doing the kind of conversion you require, ie. is simply truncating the fractional portion sufficient or do you require specific rounding etc.
In terms of performance, the cast of a double to int simply uses the conv.i4
opcode where using something like Convert.ToInt32(double) results in a function call to perform the conversion.
For decimal to int the cast will result in a call to an operator overload, essentially a function call, and of course using Convert.ToInt32(decimal) is again a function call.
In the case of decimal there is essentially no difference, but Convert.ToInt32(double) will not even be inlined so it is considerably more expensive, but is the cost significant in the bigger picture, typically not.
Why don't you simply use Math.Round()
for converting decimal or double to int?
Note that Math.Round()
still returns decimal / double but now properly rounded, so you can cast it to int
.
精彩评论