Link to home
Create AccountLog in
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
SOLUTION
Avatar of LeeeRussell
LeeeRussell
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of IssacJones
IssacJones

ASKER

Many thanks
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]