将数字舍入为特定分辨率

pax*_*blo 0 language-agnostic resolution rounding

我知道很多语言都能够舍入到一定数量的小数位,例如使用Python:

>>> print round (123.123, 1)
    123.1
>>> print round (123.123, -1)
    120.0
Run Code Online (Sandbox Code Playgroud)

但是我们如何舍入到不是十进制倍数的任意分辨率.例如,如果我想将数字四舍五入到最接近的一半或三分之一,那么:

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.
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 8

您可以通过简单地缩放数字来舍入到任意分辨率,即将数字乘以除以分辨率的数字(或者更容易,只需除以分辨率).

然后将其四舍五入到最接近的整数,然后再缩放它.

在Python(这也是一种非常好的伪代码语言)中,它将是:

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)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,它是roundPartial提供功能的功能,并且应该很容易将其转换为具有round函数的任何过程语言.

其余部分,基本上是测试工具,输出:

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
Run Code Online (Sandbox Code Playgroud)