0

I have two float values 1000.4 and 700.7

The result of 1000.4 - 700.7 returns me 299.69999999999993. I did my research,Decimal would be a good option to do the calculation here print(Decimal('1000.4') - Decimal('700.7')) and it returns 299.7

I have a question. what if I have a value 14.5 how can I print it as 14.50?

I tried getcontext().prec = 2 and it didn't help and would made the print(Decimal('1000.4') - Decimal('700.7')) returns 3.0E+2 which isn't what I want.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125

2 Answers2

2

You can use f-strings to custom the leading zeros/limit the precision.

n=14.5
print(f"{n:.2f}")

Here, it would print only the first two decimals. (14.50).

Jonathan1609
  • 1,809
  • 1
  • 5
  • 22
1

This can be done with formatting for both floats and Decimal.

In [1]: print("{:.2f}".format(1.234))
1.23

In [2]: from decimal import Decimal

In [3]: print("{:.2f}".format(Decimal(1.234)))
1.23
theherk
  • 6,954
  • 3
  • 27
  • 52