开发者

Problem with Rounding off to nearest 0.05 value

开发者 https://www.devze.com 2023-03-13 03:30 出处:网络
There are already so many questions asked about this already. One popular answer is to use the below formula.

There are already so many questions asked about this already.

One popular answer is to use the below formula.

  Math.ceiling(myValue * 20) / 20

I need the following output for corresponding input.

     16.489 (input)   - 16.49(output)

Using the above form开发者_高级运维ula

     16.489*20  = 329.78

     Math.ceil(329.78) = 330.0

     and 330.0 /20  = 16.5 

but what I want is 16.49.

Ideally the Math.ceil stuff should have given 329.8

So how do we get around the above case? There are many other cases similar to this.


Instead of multiplying / dividing with 2*10, you should do it with 102.

However, I suggest you use Math.round(100*a) / 100.0, or if you need it for printing, printf or DecimalFormat.

Examples:

double input = 16.489;

// Math.round
System.out.println(Math.round(100 * input) / 100.0);

// Decimal format
System.out.println(new DecimalFormat("#.##").format(input));

// printf
System.out.printf("%.2f", input);

Output:

16.49
16.49
16.49


Why not use Math.round() to format your value?

edit: Math.round(value * 100.0) / 100.0;


I think this would help you.This link gives you a discussion on how to round off a number to the n-th decimal place.


Rounding 16.489 up to the nearest 0.05 is correctly 16.5, with 16.45 being the next lowest possible value.

The behaviour seen is correct. If you want to be able to round up to the nearest 0.01 then

Math.ceiling(myValue * 100) / 100

would be a more appropriate solution.


try this

round(16.489, 2, BigDecimal.ROUND_CEILING);

public static double round(double x, int scale, int roundingMethod) {
        try {
            return (new BigDecimal
                   (Double.toString(x))
                   .setScale(scale, roundingMethod))
                   .doubleValue();
        } catch (NumberFormatException ex) {
            if (Double.isInfinite(x)) {
                return x;
            } else {
                return Double.NaN;
            }
        }
    }
0

精彩评论

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