sachin
sachin

Reputation: 1457

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.

thanks in advance....

Upvotes: 1

Views: 2374

Answers (6)

Nupur
Nupur

Reputation: 43

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() {
}

}

Upvotes: 0

lschin
lschin

Reputation: 6811

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, ...).

Upvotes: 2

Lorenzo Manucci
Lorenzo Manucci

Reputation: 880

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

Upvotes: 1

mKorbel
mKorbel

Reputation: 109823

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() {
    }
}

Upvotes: 1

benqus
benqus

Reputation: 1149

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?

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533870

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;

Upvotes: 4

Related Questions