0

I want to Round to the nearest integer if absolute difference to the nearest integer is less or equal than 0.01,

my code is with the test:

import unittest

def round_price(price):

  if abs(price - round(price)) <= 0.01:
    price = int(round(price))
  return price


class TestRounding(unittest.TestCase):
  def test_rounding(self):
    self.assertEqual(round_price(15.98), 15.98)
    self.assertEqual(round_price(15.99), 16)
    self.assertEqual(round_price(16.00), 16)
    self.assertEqual(round_price(16.01), 16)
    self.assertEqual(round_price(16.02), 16.02)

if __name__ == '__main__':
unittest.main()

Im still getting an error when testing,

self.assertEqual(round_price(16.01), 16) AssertionError: 16.01 != 16

Rami Wafai
  • 71
  • 1
  • 9

2 Answers2

1

You need to compare the difference between the price and the rounded price:

def round_price(price):

  if abs(price - round(price)) <= 0.01:
    price = int(round(price))
  return price
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0
def round_price(price):

    if abs(price - round(price)) <= 0.01000001:
        price = round(price)
    return price
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
Rami Wafai
  • 71
  • 1
  • 9