How to I write a function that approximates a double in the following manner, returning an int:
function (2.3) -> 2
function (2.7) -> 3
function (-1.2) -> -1
function (-1.7) -> -2
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.
Is this homework?
Because there’s a library function to do this: Math.round()
If you’re actually trying to implement something close to this yourself, one way to do so is to take the double and explicitly cast it into an int.
For the case of positive numbers, this would essentially truncate it (e.g., 5.99 becoming 5.00).
Now you can cast it back to double, and deduct it from your original number. This would leave you with a number between 0 and 0.99…
Compare it to 0.50 and decide whether to round up or round down. If you round down, take the truncated number, otherwise take the truncated + 1.