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:
- If there is no number before the floating point, then need to add leading zero.
- Truncate decimal digits after the floating point to a fixed width.
- Add trailing decimal zero’s to make it to fixed width.
- 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.
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:
- What is %matplotlib inline and how to use ?
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Linux: sudo: apt-get: command not found
- Convert negative to positive number in Python
- Putty Fatal Error No supported authentication methods available
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Build a Docker Image with a Dockerfile and Cloud Build in GCP?
- Is it possible to change Google Cloud Platform Project ID ?
- Error: helm install unknown flag: –name
- Install Python 3 on Windows 10 machine
- Can I use multiple values.yaml files for Helm Chart ?
- TypeError: a bytes-like object is required, not ‘str’ – Python3