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

How to round numbers in place in a string in python

I’d like to take some numbers that are in a string in python, round them to 2 decimal spots in place and return them. So for example if there is:

"The values in this string are 245.783634 and the other value is: 25.21694"

I’d like to have the string read:

"The values in this string are 245.78 and the other value is: 25.22"

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

>Solution :

You can use the re module to find all the floating point numbers in the string, and then use the round() function to round them to the desired number of decimal places. Here is an example of how you can do this:

import re

def round_numbers_in_string(string, decimal_places):
    # find all floating point numbers in the string
    numbers = [float(x) for x in re.findall(r"[-+]?\d*\.\d+|\d+", string)]
    # round the numbers to the desired decimal places
    rounded_numbers = [round(x, decimal_places) for x in numbers]
    # replace the original numbers with the rounded numbers in the string
    for i, num in enumerate(numbers):
        string = string.replace(str(num), str(rounded_numbers[i]))
    return string

original_string = "The values in this string are 245.783634 and the other value is: 25.21694"
decimal_places = 2
rounded_string = round_numbers_in_string(original_string, decimal_places)
print(rounded_string)

OUTPUT:

The values in this string are 245.78 and the other value is: 25.22
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