Solved

decimal places in a string

Posted on 2011-09-08
4
486 Views
Last Modified: 2012-05-12
Hi

I have a decimal value which I have calculated. I want to convert this to a string but only to a certain precision e.g. 2 decimal places. Can anybody tell me how to do this?

Issac
0
Comment
Question by:IssacJones
  • 2
4 Comments
 
LVL 6

Assisted Solution

by:LeeeRussell
LeeeRussell earned 20 total points
ID: 36502271
To turn a decimal value to a string use the str() function:

a = 17.5678
b = str(a)

If you want to have it to a certain precision (with rounding) use the round() function:

c = round(a,2)
d = str(c)

Or combine it all:

Rounded_String = str(round(17.5678,2))
0
 
LVL 29

Accepted Solution

by:
pepr earned 230 total points
ID: 36502500
You probably do not want to round the value only for printing.  Also, it may be unreliable.

What you want is what is called a string interpolation or formatting string.  You can use or old way (resembling the C printf) or new way (resembling the C# way). Try the following in the interactive Python:

>>> x = 17.5678
>>> s = '%.2f' % x
>>> s
'17.57'
>>> s2 = '{:.2f}'.format(x)
>>> s2
'17.57'

Open in new window

0
 

Author Closing Comment

by:IssacJones
ID: 36502776
Many thanks
0
 
LVL 6

Expert Comment

by:LeeeRussell
ID: 36502808
The method presented by pepr does round the result.  If you truly want to truncate the result, I think you'd have to do something like:

a = 17.5678

length_of_final_string = len('%.*f' % (number_of_decimal_places, a))

b = str(a)[:length_of_final_string]
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question