Answers for "how to use decimals in python"

25

python 2 decimal places

print(format(432.456, ".2f"))

>> 432.45

print(format(321,".2f"))

>> 321.00
Posted by: Guest on March-23-2020
2

python decimal()

Decimal is a python library that allows for more precise decimals, without a 
large amount of floating point errors.
from decimal import *
getcontext().prec = n
The above line let''s you change the precision of the decimal.
i.e.
getcontext().prec = 6
print(Decimal(1) / Decimal(7))
Decimal('0.142857')
You can see that it has 6 digits of prescision.
There are useful functions, 
.log10
.sqrt
.exp
.ln
First, Decimal(x).log10 returns log10(x).
I.e.
print(Decimal(100).log10)
2
Then, Decimal(x).sqrt returns the square root of a number (duh).
Returns the square root of a number
getcontext().prec = 28
Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
Then .exp is the natural anti-lograthm (natural lograthm is loge(x), where is
e is Euler''s (say Oiler''s) constant, or 2.718...
Since exponentiation is the opposite of lograthms,
Decimal(x).exp = e**x
getcontext().prec = 3
Decimal(1).exp()
Decimal('2.718')
Finally, .ln is the natural lograthm, or loge(x) .
For more info check out 
https://docs.python.org/3/library/decimal.html
.
Posted by: Guest on July-30-2021
0

python format decimal

# 2.6 python  and newer and python 3.x
# Put desired number of decimal by changing the number inside {:.2f} bellow;
print(' {:.2f}'.format(71.428571))
71.43
# 2.6 python and older
# Put desired number of decimal by changing the number inside '%.2f' bellow;
print('%.2f'%(71.428571))
71.43
Posted by: Guest on July-29-2021
0

How to solve not in base 10 in python when using decimals

Example = float(input("Question?"))
Example_2 = float(input("Question2?"))
Awnser_1 = float(Example) * float(Example_2)
print = Awnser_1
Posted by: Guest on June-12-2020

Code answers related to "how to use decimals in python"

Python Answers by Framework

Browse Popular Code Answers by Language