2011-11-14 41 views
0

我知道很多的语言有舍入到一个特定小数位数,如使用Python的能力:舍入数到特定分辨率

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

但是我们如何四舍五入到这是一个任意分辨率不是的十进制倍数。例如,如果我想圆一个数目到最近的一半或三分之一,因此:

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. 
+0

这个问题已经被问很多次了。为什么你的代表用户会写一个全新的问题并提供你自己的答案? – Alnitak

+0

@Alnitak,如果你可以找到一个愚蠢的话,那么_标记就是这样,这就是标记的目的。我无法找到一个,并且为了响应类似的Python特定版本(舍入到四分之一),我提出了适用于任何解决方案的解决方案。我的理由是:增加好问题的答案,因为危险类型的问题和答案被认为是正确的,只要他们有效。而且这不是我寻找代表,我已经达到了每日上限:-) – paxdiablo

+0

请参阅326476和7423023 - 问题不是语言不可知的,但答案通常是 – Alnitak

回答

7

您可以轮通过简单的缩放数量,这是一个由分辨率来划分乘以数量的任意分辨率(或者更容易,只是按照决议进行划分)。

然后,在将其缩小回来之前,将它四舍五入到最接近的整数。

在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) 

在上面的代码,它是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