convert floating point number to fixed point number python

How to convert floating point number to fixed point in Python ?

This tutorial guides you on how to convert floating point number to a fixed point number in Python. Let’s say you have specific requirements in your project to format floating point number to a fixed width as discussed in the example below. Let’s see how to use Format String syntax to achieve this.

Convert floating point number to fixed point in Python

For example, Let’s say you have the following list of numbers.

numbers = [10.45, .1542678972, 5, 3.443, 6775.245, 555.3467]

And your requirement is as follows:

  1. If there is no number before the floating point, then need to add leading zero.
  2. Truncate decimal digits after the floating point to a fixed width.
  3. Add trailing decimal zero’s to make it to fixed width.
  4. Align the floating point numbers accordingly.

That is, the output should look like the following:

     10.45
      0.15
      5.00
      3.44
   6775.24
    555.35

Solution: 

Below is the code which will format the list of floating point number to the required format.

for x in numbers:
    print ("{:6.2f}".format(x))

We are using Format String Syntax of Python Strings.

Note, In the Format String Syntax,

  • x is the floating point number that needs to be formatted.
  • 6.2f is the format specification.
  • “f” denotes the width of the fixed point number.
  • Hence the total width should be “6” and the number of digits after decimal point should be “2”.

Try to run the above code in Jupyter Python Notebook, you should see the following output.

convert floating point number to fixed point number python

 

That’s it. You had learnt how to convert a floating point number to fixed point number using Python’s Format String syntax.

Hope it helped 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments