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
  • 35,097
  • 12
  • 75
  • 106
Haifeng Zhang
  • 27,283
  • 17
  • 68
  • 115

2 Answers2

1

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,630
  • 1
  • 3
  • 19
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
  • 5,196
  • 3
  • 27
  • 46