开发者

Rounding the Double Values

Rounding Issue

For Example

  1. 598.59 ya 591.45 to be convert 600.
  2. 541.0 to be convert 550.
  3. 541.59 to be convert 550.

    Just check the last 2 digit ignore the decimal value. if last 2 digit in between 11- 19 it will converted 20 if 21-29 then will converted 30 and so on..

So What can i do for this. Need ur Help.

开发者_StackOverflow中文版

thanks in advance....


I am just guessing what you mean, but assuming you want to round to the nearest n you can do the following.

double d = Math.round(d / n) * n;

e.g. if n = 50

double d = Math.round(d / 50) * 50;


Use MathUtils [Commons Math] :
- static double round(double x, int scale) or
- static double round(double x, int scale, int roundingMethod)

MathUtils.round(598.59, -1); // 600.0
MathUtils.round(591.45, -1, BigDecimal.ROUND_CEILING); // 600.0
MathUtils.round(541.0, -1, BigDecimal.ROUND_CEILING); // 550.0
MathUtils.round(541.59, -1, BigDecimal.ROUND_CEILING); // 550.0

For update in question

Just check the last 2 digit ignore the decimal value. if last 2 digit in between 11- 19 it will converted 20 if 21-29 then will converted 30 and so on..

MathUtils.round((double) 111, -1, BigDecimal.ROUND_UP); // 120.0
MathUtils.round((double) 119, -1, BigDecimal.ROUND_UP); // 120.0
MathUtils.round((double) 121, -1, BigDecimal.ROUND_UP); // 130.0
MathUtils.round((double) 129, -1, BigDecimal.ROUND_UP); // 130.0

Cast to double to make sure round(double x, ...) is use, instead of round(float x, ...).


okay, so you can use the Math class. like this:

Math.floor(myNumber); //541.59 -> 541, returns double

but in this case you have to define your "limit" for rounding. What's the purpose of this?


for example

public class RoundToTwodecimalPlaces {

    public static double roundTo2Places(double value) {
        assert value >= Long.MIN_VALUE / 100 && value <= Long.MAX_VALUE / 100;
        long digits = (long) (value < 0 ? value * 100 - 0.5 : value * 100 + 0.5);
        return (double) digits / 100;
    }

    private RoundToTwodecimalPlaces() {
    }
}


598.59 ya 591.45 to be convert 600.
541.0 to be convert 550.
541.59 to be convert 550.

As for me : 1.Divide by 10

59.859
54.10
54.159

2. Round to nearest not less integer and 3. multiply by 10. Received 600 550 550


public class RoundToTwodecimalPlaces {

public static double roundTo2Places(double value) {
    assert value >= Long.MIN_VALUE / 100 && value <= Long.MAX_VALUE / 100;
    long digits = (long) (value < 0 ? value * 100 - 0.5 : value * 100 + 0.5);
    return (double) digits / 100;
}

private RoundToTwodecimalPlaces() {
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜