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 

7 Answers

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.

6

How about:

Math.round 

You could get overflow problems converting a double to an int - this actually returns a long for that reason.

1
public int homeworkFunction(double x) { return (int)(Math.signum(x) * Math.min(Math.round(Math.abs(x)) , Integer.MAX_VALUE); } 
2

Piece of cake, man:

private double round(double d, int numbersAfterDecimalPoint) { long n = Math.pow(10, numbersAfterDecimalPoint); double d2 = d * n; long l = (long) d2; return ((double) l) / n; } 

You can use the Math.round method for that, see .

I have never used Java, but I am 100 % sure there is a Round or Math.Round function to use for this!

Without Math.round(), you can use

public long homeworkFunction(double x) { return (long)(x > 0 ? x + 0.5 : x - 0.5)); } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy