Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a number to within a certain range?

Tags:

java

rounding

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?

like image 492
Florian Müller Avatar asked Oct 21 '11 15:10

Florian Müller


People also ask

How do you round numbers that meet specified criteria in Excel?

To always round up (away from zero), use the ROUNDUP function. To always round down (toward zero), use the ROUNDDOWN function. To round a number to a specific multiple (for example, to round to the nearest 0.5), use the MROUND function.

How do you round multiple cells in Excel?

ROUND Multiple Cells With ROUND FunctionInsert the ROUND formula =ROUND(B2,2) in the blank cell C2 and press Enter keyboard button. The numeric value of cell B2 will be rounded with two decimal places.


3 Answers

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
like image 183
fredley Avatar answered Oct 21 '22 17:10

fredley


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
    
like image 32
Matteo Avatar answered Oct 21 '22 17:10

Matteo


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;
} 
like image 39
Gilbert Le Blanc Avatar answered Oct 21 '22 19:10

Gilbert Le Blanc