use more decimals in python

  • Last Update :
  • Techknowledgy :
print(format(432.456, ".2f"))

   >>
   432.45

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

   >>
   321.00
#to round floats in Python you can use the "round"
function.ex:

   tax = 34.4563
tax = round(tax, 2)

#the number 2 at the end is how many digits are rounded.

#the variable "tax"
would now be: 34.46
>>> format(2.0, '.6f')
'2.000000'

Suggestion : 2

last modified July 29, 2022

1._
#!/usr/bin/python

from decimal
import Decimal

x = 1 / 3
print(type(x))
print(x)

print("-----------------------")

y = Decimal(1) / Decimal(3)
print(type(y))
print(y)

The example compars the precision of two floating point types in Python.

$ ./defprec.py
<class 'float'>
   0.3333333333333333
   -----------------------
   <class 'decimal.Decimal'>
      0.3333333333333333333333333333
3._
#!/usr/bin/python

from decimal
import Decimal

x = 0.1 + 0.1 + 0.1

print(x == 0.3)
print(x)

print("----------------------")

x = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')

print(x == Decimal('0.3'))
print(float(x) == 0.3)
print(x)

It is possible to change the default precision of the Decimal type. In the following example, we also use the mpmath module, which is a library for arbitrary-precision floating-point arithmetic.

$ pip install mpmath
6._
#!/usr/bin/python

from decimal
import Decimal, getcontext
import math

import mpmath

getcontext().prec = 50
mpmath.mp.dps = 50
num = Decimal(1) / Decimal(7)

num2 = mpmath.mpf(1) / mpmath.mpf(7)

print("   math.sqrt: {0}".format(Decimal(math.sqrt(num))))
print("decimal.sqrt: {0}".format(num.sqrt()))
print(" mpmath.sqrt: {0}".format(mpmath.sqrt(num2)))
print('actual value: 0.3779644730092272272145165362341800608157513118689214')

Suggestion : 3

Last Updated : 05 Jul, 2022

Output: 

The integral value of number is: 3
The smallest integer greater than number is: 4
The greatest integer smaller than number is: 3

Output : 

The value of number till 2 decimal place(using % ) is: 3.45
The value of number till 2 decimal place(using format()) is: 3.453
The value of number till 2 decimal place(using round()) is: 3.45

Suggestion : 4

The round() function rounds decimal places up and down. This makes 4.458 into 4.46 and 8.82392 into 8.82.,To round decimal places down we use a custom function. That turns 2.348 into 2.34.,The first rounds every list value to two decimal places (up and down) with the round() function. We put those rounded values in a new list, valuesRound.,Round decimal places up and down: round() Example: round decimal digits up and down

round(12.54673, 2)
# Returns: 12.55
# Some numerical values
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953

# Round to different decimal places
roundA = round(valueA, 5)
roundB = round(valueB, 4)
roundC = round(valueC, 3)
roundD = round(valueD, 2)
roundE = round(valueE, 1)

# Output rounded values
print("Value:".ljust(15), "Rounded:")

print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)
round_decimals_up(8.343)
# Returns: 8.35
import math

def round_decimals_up(number: float, decimals: int = 2):
   ""
"
Returns a value rounded up to a specific number of decimal places.
""
"
if not isinstance(decimals, int):
   raise TypeError("decimal places must be an integer")
elif decimals < 0:
   raise ValueError("decimal places has to be 0 or more")
elif decimals == 0:
   return math.ceil(number)

factor = 10 ** decimals
return math.ceil(number * factor) / factor
import math

def round_decimals_up(number: float, decimals: int = 2):
   ""
"
Returns a value rounded up to a specific number of decimal places.
""
"
if not isinstance(decimals, int):
   raise TypeError("decimal places must be an integer")
elif decimals < 0:
   raise ValueError("decimal places has to be 0 or more")
elif decimals == 0:
   return math.ceil(number)

factor = 10 ** decimals
return math.ceil(number * factor) / factor

# Some numbers to round
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953

# Round to values to a different number of decimal places
roundA = round_decimals_up(valueA)
roundB = round_decimals_up(valueB)
roundC = round_decimals_up(valueC)
roundD = round_decimals_up(valueD)
roundE = round_decimals_up(valueE)

# Output the results
print("Value:".ljust(15), "Rounded:")

print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)
round_decimals_down(2.348, 2)
# Or:
   round_decimals_down(2.348)
# Both
return: 2.34

Suggestion : 5

The usual start to using decimals is importing the module, viewing the current context with getcontext() and, if necessary, setting new values for precision, rounding, or enabled traps:,The constants in this section are only relevant for the C module. They are also included in the pure Python version for compatibility.,For example, the following code sets the current decimal precision to 42 places, performs a calculation, and then automatically restores the previous context:,If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').

>>> from decimal
import *
>>>
getcontext().prec = 6 >>>
   Decimal(1) / Decimal(7)
Decimal('0.142857') >>>
   getcontext().prec = 28 >>>
   Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> from decimal
import *
>>>
getcontext()
Context(prec = 28, rounding = ROUND_HALF_EVEN, Emin = -999999, Emax = 999999,
      capitals = 1, clamp = 0, flags = [], traps = [Overflow, DivisionByZero,
         InvalidOperation
      ])

   >>>
   getcontext().prec = 7 # Set a new precision
>>> getcontext().prec = 28 >>>
   Decimal(10)
Decimal('10') >>>
   Decimal('3.14')
Decimal('3.14') >>>
   Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875') >>>
   Decimal((0, (3, 1, 4), -2))
Decimal('3.14') >>>
   Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951') >>>
   Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724') >>>
   Decimal('NaN')
Decimal('NaN') >>>
   Decimal('-Infinity')
Decimal('-Infinity')
>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
         >>> Decimal('3.5') < 3.7 Traceback (most recent call last): File "<stdin>" , line 1, in <module>
            decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
               >>> Decimal('3.5') == 3.5
               True
>>> getcontext().prec = 6 >>>
   Decimal('3.0')
Decimal('3.0') >>>
   Decimal('3.1415926535')
Decimal('3.1415926535') >>>
   Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987') >>>
   getcontext().rounding = ROUND_UP >>>
   Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Suggestion : 6

An easy way to use integers and strings with decimal places is by converting them to floats. Once they are converted to floats, we can use them the same way as any other float. Note that when converting a string, the string should contain a decimal point. ,That being said, floats are not useless. Being the default Python decimal manager, we can easily set our precision in floating point values, easily specifying the number of decimal places. ,The three following methods remove all decimal places by converting our float into an integer.,We have other ways to construct decimal instances using floats, integers, strings, and tuples. We’ll cover the decimal module and the construction of those instances later in this post.

Floats are Python’s default way of displaying numbers with decimal places. Let’s create a variable and add a value with a decimal point.

my_float = 18.50623

When we check the type of our variable, we see that Python has automatically recognized it as a float.

print(type(my_float))

Integers are numbers without any decimal places. 

my_integer = 19
print(type(my_integer))

A tuple is a collection of Python objects separated by commas.

my_tuple = (1, 8, 5, 0, 6, 2, 3)
print(type(my_tuple))

Let’s go ahead and convert our integer and our string.

my_integer = 19
my_floated_integer = float(my_integer)

print(type(my_integer))
print(type(my_floated_integer))
print(my_integer)
print(my_floated_integer)

my_string = '18.50623'
my_floated_string = float(my_string)

print(type(my_string))
print(type(my_floated_string))
print(my_string)
print(my_floated_string)