Round a number to the next HIGHEST 10

只谈情不闲聊 提交于 2019-12-04 05:10:19
if(rangeMax % 10 !=0)
   rangeMax = (rangeMax - rangeMax % 10) + 10;

You could also use Math.Round() with MidpointRounding.AwayFromZero using a decimal number (otherwise integer division will truncate fractions):

decimal number = 55M;
decimal nextHighest = Math.Round(number/ 10, MidpointRounding.AwayFromZero) * 10;

If you want to go up to the next 10, you can use Math.Ceiling as follows:

rangeMax = (int)(Math.Ceiling((decimal)rangeMax / 10) * 10);

If you need to generalize to go to the next n (for example 5 here) you can do:

int n = 5;    
rangeMax = (int)(Math.Ceiling((decimal)rangeMax / n) * n);

Something which might help is to divide the number by 10. This should round it to the nearest integer. Then multiply it by 10 again to get the number rounded to the nearest 10

I use THIS:

public static double RoundTo10(double number)
        {
            if (number > 0)
            {
                return Math.Ceiling(number / 10) * 10;
            }
            else
            {
                return Math.Floor(number / 10) * 10;
            }
        }

you can try this....

            decimal val = 95;
        //decimal val =Convert.ToDecimal( textBox1.Text);
        decimal tmp = 0;
        tmp = (val % 10);
        //MessageBox.Show(tmp.ToString()+ "Final val:"+(val-tmp).ToString());
        decimal finval = val - tmp;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!