Florian Müller
Florian Müller

Reputation: 7785

How to round a number to within a certain range?

I have a value like this:

421.18834

And I have to round it mathematical correctly with a mask which can look like this:

0.05
0.04
0.1

For example, if the mask is 0.04, i have to get the value 421.20, because .18 is nearer at .20 than .16.

All functions that I found using Google didn't work.

Can you please help me?

Upvotes: 7

Views: 4739

Answers (4)

user207421
user207421

Reputation: 310907

Contrary to all the answers you will probably get here about multiplying and dividing, you can't do this accurately because floating point doesn't have decimal places. To need to convert to a decimal radix and then round. BigDecimal does that.

Upvotes: 3

fredley
fredley

Reputation: 33901

double initial = 421.18834;
double range = 0.04;

int factor = Math.round(initial / range); // 10530 - will round to correct value

double result = factor * range; // 421.20

Upvotes: 11

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

Both fredley and Matteo make the assumption that the rounding factor is itself a factor of 100. For factors like 0.06 or 0.07, this is an incorrect assumption.

Here's my Java routine:

public double rounded(double number, double factor) {
    long integer = (long) number;
    double fraction = number - integer;
    double multiple = (fraction / factor);
    multiple = Math.round(multiple);
    return factor * multiple + integer;
} 

Upvotes: 2

Matteo
Matteo

Reputation: 14930

You don't need a special function. You multiply your original number by (1/mask), you round it to a decimal and you divide again by the same factor.

  • Example with 0.05

    factor = 1/0.05 = 20
    421.18834 * 20 =  8423.7668
    int(  8423.7668 ) = 8424
    8424.0 / 20.0 = 421.20
    
  • Example with 0.01

    factor = 1/0.1 = 10
    421.18834 * 10 = 4211.8834
    int( 4211.8834 ) = 4212
    4212.0 / 10.0 = 421.20
    

Upvotes: 3

Related Questions