How to round numbers in place in a string in python

Question:

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"
Asked By: Drthm1456

||

Answers:

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
Answered By: Awesome Ashu

You can use format strings simply

link=f'{23.02313:.2f}'
print(link)

This is one hacky way but many other solutions do exist. I did that in one of my recent projects.

Answered By: MUHAMMAD HADI

Here’s an example of how you can accomplish this in Python:

def round_numbers_in_string(string):
    # Find all numbers in the string
    numbers = re.findall(r'd+.d+', string)
    for number in numbers:
        # Round the number to 2 decimal places
        rounded_number = round(float(number), 2)
        # Replace the original number with the rounded number
        string = string.replace(number, str(rounded_number))
    return string

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

This script uses the re module to find all numbers in the string that match the pattern d+.d+, which corresponds to one or more digits, followed by a period, followed by one or more digits. The script then loops through the numbers and rounds them to 2 decimal places using the round() function. Finally, it replaces the original number with the rounded number in the string using the str.replace() method.

This script will output: "The values in this string are 245.78 and the other value is: 25.22"

Note that this script only works if numbers in the string are in format of x.yy if the format is different you need to adjust the pattern accordingly.

Answered By: ma9

Another alternative using regex for what it is worth:

import re

def rounder(string, decimal_points):
    fmt = f".{decimal_points}f"
    return re.sub(r'd+.d+', lambda x: f"{float(x.group()):{fmt}}", string)

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

print(rounder(text, 2))

Output:

The values in this string are 245.78 and the other value is: 25.22
Answered By: ScottC

What you’d have to do is find the numbers, round them, then replace them. You can use regular expressions to find them, and if we use re.sub(), it can take a function as its "replacement" argument, which can do the rounding:

import re

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

n = 2
result = re.sub(r'd+.d+', lambda m: format(float(m.group(0)), f'.{n}f'), s)

Output:

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

Here I’m using the most basic regex and rounding code I could think of. You can vary it to fit your needs, for example check if the numbers have a sign (regex: [-+]?) and/or use something like the decimal module for handling large numbers better.

Answered By: wjandrea

I’m not sure quite what you are trying to do. "Round them in place and return them" — do you need the values saved as variables that you will use later? If so, you might look into using a regular expression (as noted above) to extract the numbers from your string and assign them to variables.

But if you just want to be able to format numbers on-the-fly, have you looked at f-strings? f-string

print(f"The values in this string are {245.783634:.2f} and the other value is: {25.21694:.2f}.")

output:

The values in this string are 245.78 and the other value is: 25.22.
Answered By: Feikname
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.