How to round a decimal value to the nearest multiple of 0.10 in Python

1 Answer

0 votes
from decimal import Decimal

def round_to_nearest_multiple_of_010(n):
    remainder = n.remainder_near(Decimal('0.10'))
    return n - remainder

for n in range(90, 110):
    d = Decimal(n) / Decimal('100')
    print("{0} rounds to {1}".format(d, round_to_nearest_multiple_of_010(d)))




'''
run:

0.9 rounds to 0.90
0.91 rounds to 0.90
0.92 rounds to 0.90
0.93 rounds to 0.90
0.94 rounds to 0.90
0.95 rounds to 1.00
0.96 rounds to 1.00
0.97 rounds to 1.00
0.98 rounds to 1.00
0.99 rounds to 1.00
1 rounds to 1.00
1.01 rounds to 1.00
1.02 rounds to 1.00
1.03 rounds to 1.00
1.04 rounds to 1.00
1.05 rounds to 1.00
1.06 rounds to 1.10
1.07 rounds to 1.10
1.08 rounds to 1.10
1.09 rounds to 1.10

'''

 



answered Aug 30, 2021 by avibootz

Related questions

1 answer 120 views
1 answer 128 views
2 answers 133 views
1 answer 126 views
...