Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

round floats inside strings python

Having a str i would like to round the floats/numbers inside a given string:

i.e.:

'fooo <= 0.5615000128746033 and bar <= 567.511'

given for example the restriction of 2 decimals:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'fooo <= 0.56 and bar <= 567.51'

which will be the optimal way to do it?

I imagine a some lines of code to accomplish it, any suggestion on a more or less one liner way?

As this is about performance and oneliner, the procedure I have so far is:

# find floats from string
import re
re.findall("\d+\.\d+", 'fooo <= 0.5615000128746033 and bar <= 567.511')

# find the other non-float elements and concatenate with the rounded float strings

>Solution :

You can simply use re.sub as exactly as what follows:

import re
def rounder(flt):
  return str(round(float(flt.group())*100)/100)
example = 'fooo <= 0.5615000128746033 and bar <= 567.511'
re.sub('\d+\.\d+', rounder, example)

Output

fooo <= 0.56 and bar <= 567.51

Explanation

I have defined a function that gets the matched string and transforms it into float and round it to two decimals. This function can be used in re.sub as an argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading