Rounding integers to nearest multiple of 10 [duplicate]

有些话、适合烂在心里 提交于 2019-12-17 09:21:37

问题


I am trying to figure out how to round prices - both ways. For example:

Round down
43 becomes 40
143 becomes 140
1433 becomes 1430

Round up
43 becomes 50
143 becomes 150
1433 becomes 1440

I have the situation where I have a price range of say:

£143 - £193

of which I want to show as:

£140 - £200

as it looks a lot cleaner

Any ideas on how I can achieve this?


回答1:


I would just create a couple methods;

int RoundUp(int toRound)
{
     if (toRound % 10 == 0) return toRound;
     return (10 - toRound % 10) + toRound;
}

int RoundDown(int toRound)
{
    return toRound - toRound % 10;
}

Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.




回答2:


You don't need to use modulus (%) or floating point...

This works:

public static int RoundUp(int value)
{
    return 10*((value + 9)/10);
}

public static int RoundDown(int value)
{
    return 10*(value/10);
}



回答3:


This code rounds to the nearest multiple of 10:

int RoundNum(int num)
{
     int rem = num % 10;
     return rem >= 5 ? (num - rem + 10) : (num - rem);
}

Very simple usage :

Console.WriteLine(RoundNum(143)); // prints 140
Console.WriteLine(RoundNum(193)); // prints 190



回答4:


Divide the number by 10.

number = number / 10;
Math.Ceiling(number);//round up
Math.Round(number);//round down

Then multiply by 10.

number = number * 10;



回答5:


A general method to round a number to a multiple of another number, rounding away from zero.

For integer

int RoundNum(int num, int step)
{
    if (num >= 0)
        return ((num + (step / 2)) / step) * step;
    else
        return ((num - (step / 2)) / step) * step;
}

For float

float RoundNum(float num, float step)
{
    if (num >= 0)
        return floor((num + step / 2) / step) * step;
    else
        return ceil((num - step / 2) / step) * step;
}

I know some parts might seem counter-intuitive or not very optimized. I tried casting (num + step / 2) to an int, but this gave wrong results for negative floats ((int) -12.0000 = -11 and such). Anyways these are a few cases I tested:

  • any number rounded to step 1 should be itself
  • -3 rounded to step 2 = -4
  • -2 rounded to step 2 = -2
  • 3 rounded to step 2 = 4
  • 2 rounded to step 2 = 2
  • -2.3 rounded to step 0.2 = -2.4
  • -2.4 rounded to step 0.2 = -2.4
  • 2.3 rounded to step 0.2 = 2.4
  • 2.4 rounded to step 0.2 = 2.4



回答6:


public static int Round(int n)
        {
            // Smaller multiple 
            int a = (n / 10) * 10;

            // Larger multiple 
            int b = a + 10;

            // Return of closest of two 
            return (n - a > b - n) ? b : a;
        }


来源:https://stackoverflow.com/questions/15154457/rounding-integers-to-nearest-multiple-of-10

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