Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,966 questions

51,908 answers

573 users

How to use decimal in Python

6 Answers

0 votes
from decimal import Decimal

decimal = Decimal(3.14159)
print(decimal)

result = decimal * 17
print(result)  





'''
run:

3.14158999999999988261834005243144929409027099609375
53.40702999999999800451178089

'''

 



answered Jul 10, 2022 by avibootz
0 votes
from decimal import Decimal

x = Decimal('0.2')
y = Decimal('0.2')
z = Decimal('0.2')

result = x + y + z

print(result)





'''
run:

0.6

'''

 



answered Jul 10, 2022 by avibootz
0 votes
from decimal import Decimal

x = Decimal('2.19')
y = Decimal('3.99')
print(round(x, 1))
print(round(y, 1))

a = Decimal('2.15')
b = Decimal('3.55')
print(round(a, 1))
print(round(b, 1))






'''
run:

2.2
4.0
2.2
3.6

'''

 



answered Jul 10, 2022 by avibootz
0 votes
from decimal import Decimal
import decimal

context = decimal.getcontext()
context.rounding = decimal.ROUND_HALF_DOWN


x = Decimal('2.19')
y = Decimal('3.99')
print(round(x, 1))
print(round(y, 1))

a = Decimal('2.15')
b = Decimal('3.55')
print(round(a, 1))
print(round(b, 1))






'''
run:

2.2
4.0
2.1
3.5

'''

 



answered Jul 10, 2022 by avibootz
0 votes
from decimal import Decimal

pi = Decimal((0, (3, 1, 4), -2) # 314 x 10^-2

print(pi)






'''
run:

3.14

'''
 

 



answered Jul 10, 2022 by avibootz
0 votes
from decimal import Decimal

d = Decimal(0.1)

print(d)






'''
run:

0.1000000000000000055511151231257827021181583404541015625

'''

 



answered Jul 10, 2022 by avibootz
...