Saleh Feek
Saleh Feek

Reputation: 2076

In Java, how to achieve this type of number rounding?

I am writing a small physics app. What I am planning to do is to make number rounding. The issue is that it is not a fixed rounding, but rather a variable rounding that depends on the value of the decimal digits. I will give an explanation for the issue.

I need to play this rounding while working with BigDecimal because it is a requirement for my needs.

Upvotes: 5

Views: 312

Answers (2)

ajb
ajb

Reputation: 31699

I think this will work, based on experimentation, if I understand correctly what you want. If d is a BigDecimal that contains the number:

BigDecimal rounded = d.round(new MathContext
    (d.scale() - d.precision() < 5 
        ? d.precision() - d.scale() + 5 
        : 5));

Upvotes: 4

desperateCoder
desperateCoder

Reputation: 700

Is this, what you are looking for?

public static void main(String[] args){
     double d = 0.000000000000120006130031;

     System.out.println(round(d, 5));
 }

 private static double round(double d, int precision) {
    double factor = Math.pow(10D, precision);
    int value = (int)d;
    double re = d-value;


    if (re * factor <= 0.1 && d != 0) {
        while (re * factor <= 0.1) {
            factor *= 10;
        }
        factor *= Math.pow(10D, precision);
    }
    re = ((int)(re*factor))/factor+value;

    return re;
}

(sorry, it's a little quick & dirty, but you can improve it, if you want)

EDIT: make it <= in the conditions, this should work better

Upvotes: -2

Related Questions