Precise processing in Python



1. trunc (): — This function is used to remove the entire decimal part of a floating point number and return an integer without the decimal part.

2 … ceil (): — This function is used to output the smallest integer greater than a given number .

3. floor (): — This function is used to output the largest integer less than the specified integer .

Output:

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

Setting Accuracy

There are many ways to set the correct a number of floating point values. Some of these are discussed below.

1. Using “%” : — the “%” operator is used for formatting as well as setting precision in python. This is similar to the “printf” statement in C .

2. Using format (): — is another way to format a string to set precision.

3. Using round (x, n): — This function takes 2 arguments, a number and the number to which we want to round the decimal part.

# Python code to demonstrate ceil (), trunc ()
# and gender ()

 
# import & quot; math & quot; for exact function

import math

 
# initialization value

a = 3.4536

 
# using trunc () to print an integer after truncation

print ( "The integral value of number is:" , end = "")

print (math.trunc (a))

 
# using ceil () to print the number after ceiling

print ( " The smallest integer greater than number is: " , end = " ")

print (math.ceil (a))

 
# using floor () to print the number after the floor

print ( "The greatest integer smaller than number is:" , end = "")

print (math.floor (a))

# Python code to demonstrate accuracy
# and round ()

 
# initialization value

a = 3.4536

 
# using & quot;% & quot; to print a value up to 2 decimal places

print ( " The value of number till 2 decimal place (using%) is: " , end = "")

print ( `% .2f` % a)

 
# using format () to output the value to 2 decimal places

print ( "The value of number till 2 decimal place (using format ()) is:" , end = "")

print ( "{0: .2f}" . format (a))

 
# using round () to print up to 2 decimal places

print ( "The value of number till 2 decimal place (using round ()) is:" , end = "")

print ( round (a, 2 ))

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.45 The value of number till 2 decimal place (using round ()) is: 3.45 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.