Another .NET Developers Blog


Rounding numbers to the nearest x.
March 26, 2008, 7:03 pm
Filed under: .net, programming | Tags: ,

Today we came across a very simple rounding problem: round a number up to the nearest 0.05.

A quick search came up with quite a few hints, but no concrete answer. So we rolled our own. Here’s the code.


using System;

namespace Util
{
    public class MathHelper
    {
        public static double RoundNumberUp(double number, double roundingFactor)
        {
            double rounded = RoundNumber(number, roundingFactor);
            if ((number - rounded) > 0)
            {
                rounded = rounded + roundingFactor;
            }

            return rounded;
        }

        public static double RoundNumber(double number, double roundingFactor)
        {
            double rounded = Math.Round(number * (1 / roundingFactor)) / (1 / roundingFactor);

            return rounded;
        }
    }
}

And here are the tests, which show how to use the class.


using NUnit.Framework;
using Util;

namespace Util.Tests
{
    [TestFixture]
    public class MathHelperTests
    {
        [Test]
        public void Should_round_a_number_up_to_the_nearest_0_05()
        {
            double result = MathHelper.RoundNumberUp(6.66, 0.05);
            Assert.AreEqual(6.7, result, 0.001);

            result = MathHelper.RoundNumberUp(6.7, 0.05);
            Assert.AreEqual(6.7, result, 0.001);

            result = MathHelper.RoundNumberUp(6, 0.05);
            Assert.AreEqual(6, result, 0.001);

            result = MathHelper.RoundNumberUp(6.13, 0.05);
            Assert.AreEqual(6.15, result, 0.001);

            result = MathHelper.RoundNumberUp(6.18, 0.05);
            Assert.AreEqual(6.2, result, 0.001);
        }
    }
}

Hope this comes in handy! Bye for now.


No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>