How to round a number to within a certain range?

怎甘沉沦 提交于 2019-12-22 05:12:03

问题


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?


回答1:


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



回答2:


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
    



回答3:


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;
} 



回答4:


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.



来源:https://stackoverflow.com/questions/7851492/how-to-round-a-number-to-within-a-certain-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!