2010-11-24 3 views
11

Hvor私はアンのpython以下の丸め行うことができます。最寄りの05進パイソン - 最寄りのラウンド05

7,97に

ラウンドを - > 7,95

6,72 - > 6,70

31,06 - > 31,05

36,04 - > 36,05

5,25 - > 5,25

希望します。

+0

を私は '20マジック・ナンバーを利用答えのどれも驚いていませんなぜそれが選ばれたのか説明するのは気にならない。 – martineau

+3

@martineau:誰かがそれを練習できない場合に備えて、私はここに記録します。 '20 == 1/0.05' –

答えて

24
def round_to(n, precision): 
    correction = 0.5 if n >= 0 else -0.5 
    return int(n/precision+correction) * precision 

def round_to_05(n): 
    return round_to(n, 0.05) 
+0

ありがとう!それは完璧です! – pkdkk

+0

'round_to_05(-1)'は '-0.95'を返します。これは私にとって正しい結果ではないようです。 –

+0

真実、私は自然数で考えていた...私はそれを修正します。 – fortran

12
def round05(number): 
    return (round(number * 20)/20) 

以上を総称:

def round_to_value(number,roundto): 
    return (round(number/roundto) * roundto) 

唯一の問題はbecause you're using floats you won't get exactly the answers you want次のとおりです。そこ

>>> round_to_value(36.04,0.05) 
36.050000000000004 
+1

'decimal'はPython標準ライブラリのモジュールの名前なので、その名前を使わないでください。 – martineau

+0

@martineau - あなたは正しいですし、2番目の引数が10進数である必要はないので、悪い名前でもあります。関数を使って整数に丸めることもできます。 'round_to_value(36.04,5)'は '35.0'を返す。 –

+0

+1これは現在のところ、一般化された解を提供する唯一の解答です(これは、驚くことではありませんが、一般的にはより良いIMHOです)。 – martineau

2

私達は行きます。

round(VALUE*2.0, 1)/2.0 

よろしく

+1

は半分に丸めますので、20倍 – fortran

2

は、ここに1つのライナー

def roundto(number, multiple): 
    return number+multiple/2 - ((number+multiple/2) % multiple) 
-1

受け入れ答えの延長です。あなたがしたい正確にどのようにそれをラウンドに

def round_to(n, precision): 
    correction = precision if n >= 0 else -precision 
    return round(int(n/precision+correction)*precision, len(str(precision).split('.')[1])) 


test_cases = [101.001, 101.002, 101.003, 101.004, 101.005, 101.006, 101.007, 101.008, 101.009] 
[round_to(-x, 0.003) for x in test_cases] 
[-101.001, -101.001, -101.001, -101.004, -101.004, -101.004, -101.007, -101.007, -101.007] 
1

>>> def foo(x, base=0.05): 
...  return round(base*round(x/base), 2) 

>>> foo(5.75) 
5.75 
>>> foo(5.775) 
5.8 
>>> foo(5.77) 
5.75 
>>> foo(7.97) 
7.95 
>>> foo(6.72) 
6.7 
>>> foo(31.06) 
31.05 
>>> foo(36.04) 
36.05 
>>> foo(5.25) 
5.25 
0

ラムダ関数の使用:

>>> nearest_half = lambda x: round(x * 2)/2 
>>> nearest_half(5.2) 
5.0 
>>> nearest_half(5.25) 
5.5 
>>> nearest_half(5.26) 
5.5 
>>> nearest_half(5.5) 
5.5 
>>> nearest_half(5.75) 
6.0 
関連する問題