What is the best way to convert a double to an int? Should a cast be used?
What is the best way to convert a double to an int ? Should
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use a cast if you want the default truncate-towards-zero behaviour. Alternatively, you might want to use
Math.Ceiling,Math.Round,Math.Flooretc – although you’ll still need a cast afterwards.Don’t forget that the range of
intis much smaller than the range ofdouble. A cast fromdoubletointwon’t throw an exception if the value is outside the range ofintin an unchecked context, whereas a call toConvert.ToInt32(double)will. The result of the cast (in an unchecked context) is explicitly undefined if the value is outside the range.