Hi, newbie to python here, I just wanted to ask how I can compute the after tax price and displaying only up to 2 decimal places. Like 4.1895030939393 will display only 4.18 without it rounding.

Here's what I've done so far

Original_Price = float(input('Please input the before-tax price : '))
Final_Price = (1.05*Original_Price)
print("Your total including tax is", Final_Price)

Dani AI

Generated

The replies already cover the basic choices: suggested round() and showed string formatting — both perform rounding (not truncation). and offered quick hacks to force a 4.18 result; those work in simple cases but are brittle because floating-point imprecision and different rounding rules can produce surprising results.

For robust, money-safe truncation use the Decimal type and an explicit rounding mode. This keeps arithmetic exact and makes the intention clear:

from decimal import Decimal, ROUND_DOWN

price = Decimal('4.1895030939393')
total = price * Decimal('1.05')
truncated = total.quantize(Decimal('0.00'), rounding=ROUND_DOWN)

print(f"Your total including tax is {truncated}")  # shows 4.18

An alternative that avoids floats is integer-cent arithmetic (store amounts as whole cents), or use Decimal to convert to cents and then truncate to an integer before converting back. These approaches avoid binary floating-point surprises that affect round() and simple int(...) hacks.

Notes and cautions: Python 3’s round() uses “banker’s rounding” (round-half-to-even), so behavior at exact .5 may be unexpected. For financial code, follow the applicable business or legal rounding rules (round per line item vs. final total, whether to always round toward zero, etc.) and keep values in Decimal or integer cents until the final display. Formatting functions (f-strings or format) change only presentation; apply truncation first if a non-rounded display is required.

Recommended Answers

All 4 Replies

u can use the python built in function round()

Original_Price = float(input('Please input the before-tax price : '))
Final_Price = (1.05*Original_Price)
print("Your total including tax is", round(Final_Price, 2) )

you can find out more about it here

There is also format()

>>> p = 4.1895030939393
>>> print("Your total including tax is {:.2f}.".format(p))
Your total including tax is 4.19.

If you really want 4.18 you can try ...

p = 4.1895030939393

print(round(p-0.005, 2))

or

   print(int(p*100)/100.)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.