Numbers are important part of the applications development. We use different type of numbers in different situations. We use
int for integers where there is no floating point. We can use floating point type for floating point numbers. In this tutorial we will learn floating numbers.
Define Floating Point Number
We can define floating point number like other variable types in Python but we should also add point
. between decimal and floating part like below.
a=1.1 b = 0.333 c = 12312.34346
Precision means how many digits are used in floating point part. If there are a lot of digits it is called high precision like below.
a = 12.353546656576778
If the digits are less in the floating point are we call it low precision.
a = 1.33
Format Floating Point Number
As we learn that high precision floating point numbers can have a lot of digits which may be unnecessary for most of the situations like printing and listing. In this situations we should only show some meaningful part of the floating point number. We will use
format function for this.
Set Digit Count After Point to Show
We can also set total digit count before and after point to show. This is very useful if we have a textbox which have limited character length to show. We will use
.10g parameter in order to show total 10 digits which includes before point.
pi = 3.141592653589793 format( pi , '.10g') #'3.141592654'
Set Total Digit Count to Show
We can set digit count to show after point. This will made listing floating point numbers more clearly. In this example we will only show
2 digits after point.
format( pi , '.2f') #3.14