Skip to content

Instantly share code, notes, and snippets.

@richardARPANET
Created September 10, 2020 15:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardARPANET/7480a00397d36e3d75cd98d607a5a089 to your computer and use it in GitHub Desktop.
Save richardARPANET/7480a00397d36e3d75cd98d607a5a089 to your computer and use it in GitHub Desktop.
For product pricing. Round to 'attractive' prices which don't scare off customers, e.g. 10.99, 10.50, 10.00, 9.95, etc.
from decimal import Decimal
def round_to_attractive_price(
value, attractive_after_decimals=(0, 50, 95, 99)
):
rounded = round(Decimal(value), 2)
before_decimal, after_decimal = str(rounded).split('.')
after_decimal = min(
attractive_after_decimals,
key=lambda num: abs(num - int(after_decimal))
)
return Decimal(f'{before_decimal}.{after_decimal}')
"""
from decimal import Decimal
import pytest
from round_price import round_to_attractive_price
@pytest.mark.parametrize('value, expected_value', [
(Decimal('10.22'), Decimal('10.00')),
(Decimal('10.43'), Decimal('10.50')),
(Decimal('1.88'), Decimal('1.95')),
(Decimal('1.98'), Decimal('1.99')),
(Decimal('0.15'), Decimal('0.00')),
(Decimal('0.96'), Decimal('0.95')),
])
def test_round_to_attractive_price(value, expected_value):
assert round_to_attractive_price(value=value) == expected_value
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment