Search code examples
language-agnosticresolutionrounding

Rounding numbers to a specific resolution


I know many languages have the ability to round to a certain number of decimal places, such as with the Python:

>>> print round (123.123, 1)
    123.1
>>> print round (123.123, -1)
    120.0

But how do we round to an arbitrary resolution that is not a decimal multiple. For example, if I wanted to round a number to the nearest half or third so that:

123.123 rounded to nearest half is 123.0.
456.456 rounded to nearest half is 456.5.
789.789 rounded to nearest half is 790.0.

123.123 rounded to nearest third is 123.0.
456.456 rounded to nearest third is 456.333333333.
789.789 rounded to nearest third is 789.666666667.

Solution

  • You can round to an arbitrary resolution by simply scaling the number, which is multiplying the number by one divided by the resolution (or, easier, just dividing by the resolution).

    Then you round it to the nearest integer, before scaling it back.

    In Python (which is also a very good pseudo-code language), that would be:

    def roundPartial (value, resolution):
        return round (value / resolution) * resolution
    
    print "Rounding to halves"
    print roundPartial (123.123, 0.5)
    print roundPartial (456.456, 0.5)
    print roundPartial (789.789, 0.5)
    
    print "Rounding to thirds"
    print roundPartial (123.123, 1.0/3)
    print roundPartial (456.456, 1.0/3)
    print roundPartial (789.789, 1.0/3)
    
    print "Rounding to tens"
    print roundPartial (123.123, 10)
    print roundPartial (456.456, 10)
    print roundPartial (789.789, 10)
    
    print "Rounding to hundreds"
    print roundPartial (123.123, 100)
    print roundPartial (456.456, 100)
    print roundPartial (789.789, 100)
    

    In that above code, it's the roundPartial function which provides the functionality and it should be very easy to translate that into any procedural language with a round function.

    The rest of it, basically a test harness, outputs:

    Rounding to halves
    123.0
    456.5
    790.0
    Rounding to thirds
    123.0
    456.333333333
    789.666666667
    Rounding to tens
    120.0
    460.0
    790.0
    Rounding to hundreds
    100.0
    500.0
    800.0