153

7
Q:

## How to approximate double ?

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
``````
+2  A:

``````Math.round
``````

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

Not to be pedantic, but it's not overflow that's the concern. Casting from a double to int or long equally just returns the closest value; if the double is really big it'll be Integer.MAX_VALUE or Long.MAX_VALUE. They use long just to be more precise and reduce the chance.
+1  A:

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

+4  A:

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.

The standard method of doing this is `truncate(x + .5)`. If the decimal portion of the original number is < .5, then the integer portion will remain the same. Otherwise, it will be the next greater integer.
@jamessan: But that would require access to a truncate which I'm guessing OP doesn't have since he also can't round. But generally that would save a step, that's true.
Therefore wouldn't "(int)(x+0.5)" work?
Yea, it should, I overcomplicated it, as I've stated in my reply to jamessan.
`System.out.println((int)(-1.7 + 0.5))` prints `-1`, not `-2`.
@MarkPeters: Right, you have to know the sign of `x` and adjust accordingly, just like Uri mentioned in his post -- `For the case of positive numbers, ...`.
For money there is also the case of rounding even numbers and a half differently from uneven numbers and a half.
`(int)(x+ sign(x)*0.5)` should work
+2  A:
+1  A:
``````public int homeworkFunction(double x) {
return (int)(Math.signum(x) * Math.min(Math.round(Math.abs(x)) , Integer.MAX_VALUE);
}
``````
Still doesn't do it as requested. Use Math.round instead of Math.floor and you've got it.
Yes you are correct, didnt look carefully at the sample data.
+2  A:

Without Math.round(), you can use

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

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;
}
``````