Avatar of IssacJones
IssacJones

asked on 

decimal places in a string

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
Python

Avatar of undefined
Last Comment
LeeeRussell
SOLUTION
Avatar of LeeeRussell
LeeeRussell
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of IssacJones
IssacJones

ASKER

Many thanks
Avatar of LeeeRussell
LeeeRussell
Flag of United Kingdom of Great Britain and Northern Ireland image

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]
Python
Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

6K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo