0

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"
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Drthm1456
  • 409
  • 9
  • 17

4 Answers4

0

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ScottC
  • 3,941
  • 1
  • 6
  • 20
0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

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.
Feikname
  • 119
  • 1
  • 6
-1

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.