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"
>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