RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Fixed Decimal Places

Mon Nov 16, 2015 10:23 am

I have some code that produces a number.
I am able to display this number with many decimal places or as an integer but I would like to display it with 3 digits (and another number with 2 digits).
I then convert these numbers to strings to output them onto an LCD.

Could someone please advise me if there is an easy way of setting the number of decimal places.
Thanks

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: Fixed Decimal Places

Mon Nov 16, 2015 11:05 am

Lots of languages have printf-style formatting:

python

Code: Select all

$ python -c 'import math;print("%.2f" % math.pi)'
3.14
$ python -c 'import math;print("%.3f" % math.pi)'
3.142
bash

Code: Select all

$ printf %.2f\\n 1.23456
1.23
$ printf %.3f\\n 1.23456
1.235

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Fixed Decimal Places

Mon Nov 16, 2015 12:05 pm

@sprinkmeier
Thank you for your response.
It is the Python version that I require.
I have seen that type of command but I don't know how to use it.

For example, I have a variable called averagee, that I want to be able to print to screen with 2 decimal places but also to convert to a string, for output to the LCD.

I also have a variable called totalpulse, that I want to print to screen with 3 decimal places but also convert to a string, for output to the LCD.

I am already able to send the output to the LCD. It is just the decimal places that are causing me problems.

User avatar
RogerW
Posts: 293
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Fixed Decimal Places

Mon Nov 16, 2015 12:28 pm

if x contains the number
s = '{:0.3f}'.format(x)
will create a string s containing the number formatted with 3 decimal places

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Fixed Decimal Places

Mon Nov 16, 2015 1:20 pm

@RogerW
Brilliant!
That is exactly what I wanted.
Thank you.

Return to “Python”