Double to int rounding normal way from .5 [duplicate]

故事扮演 提交于 2019-12-13 04:35:59

问题


I'm making calculation and for that I'm using the following expression:

Player.targetx = (int) (((e.getX() - Frame.x)/(Screen.myWidth/World.worldWidth))-8);

For example:

if the values are (((103 - 40)/(1184/15))-8) the double answer is around -7.20186. Player.targetx still gets value of -8.

Why's that? I would like to make it so that -7.5 gives me answer of -8 and anything like -7,499999 gives answer of -7.


回答1:


Casting to int always truncates towards 0. To round, you can use Math.round() instead. However, that always rounds halves up:

class Test {
    public static void main(String[] args) {
        System.out.println(Math.round(-7.7)); // -8
        System.out.println(Math.round(-7.5)); // -7
        System.out.println(Math.round(-7.2)); // -7

        System.out.println(Math.round(+7.2)); // 7
        System.out.println(Math.round(+7.5)); // 8
        System.out.println(Math.round(+7.7)); // 8
    }
}

Are you sure you want to round halves away from zero? If so, Math.round() won't quite do what you want. You could write your own method though:

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

This will always round away from zero, by either adding or subtracting 0.5 first (depending on the sign) and then truncating towards 0. That produces the same values as before, except that -7.5 is rounded to -8.

EDIT: I suspect the remaining problem is almost certainly due to the division being performed in integer arithmetic. We don't know the types of any of your values, but I suspect they're all int, which would lead to that problem. If you make either of the operands of the division double, it will perform the division in double arithmetic instead. The easiest way to do that - which would also increase readability - is probably to extract some of the expressions to separate variables, and cast where necessary:

double xDifference = e.getX() - Frame.x;
double widthRatio = Screen.myWidth / (double) World.worldWith;
double x = (xDifference / widthRatio) - 8;
Player.targetx = (int) Math.round(x);

If that still doesn't work, at least you'll have a much easier time seeing what's wrong.




回答2:


The final cast to int causes the result to be rounded. Try changing that cast to double. Or maybe consider using a DecimalFormat for more precise formatting.



来源:https://stackoverflow.com/questions/21077151/double-to-int-rounding-normal-way-from-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!