Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding using regular expressions

Tags:

regex

decimal

Is it possible to use a regular expression to perform rounding on a number? The problem is that I've got a lot of numbers to more than 2 decimal places in a file and I need to move them to 2 decimal places.

It's in source file so ideally I'd like to use Visual Studio's find and replace, but I'm not against the idea of writing a script to run on the file (treating it as plain text) if regex doesn't have the answer.

like image 283
Matthew Steeples Avatar asked Sep 28 '11 13:09

Matthew Steeples


People also ask

What is regular rounding?

When using conventional rounding, each count is rounded to the nearest multiple of a fixed base. Context: For example, using a base of 5, counts ending in 1 or 2 are rounded down and replaced by counts ending in 0 and counts ending in 3 or 4 are rounded up and replaced by counts ending in 5.

How do you round with decimals?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.


2 Answers

You can't do it with regexes alone, as Ryan pointed out, but you can use regexes to find decimals in your input and use a callback function on the replace operation.

In Python:

>>> import re
>>> text = "1.234 and 99.999; .555 12.345"
>>> simpledec = re.compile(r"\d*\.\d+")
>>> def mround(match):
...     return "{:.2f}".format(float(match.group()))
...
>>> re.sub(simpledec, mround, text)
'1.23 and 100.00; 0.56 12.35'

The regex to match decimals is very simplistic; it doesn't match exponential notation, for example, but it should give you an idea.

like image 173
Tim Pietzcker Avatar answered Oct 18 '22 15:10

Tim Pietzcker


Well... at least you can search for (\d+\.\d\d\d)\d* and replace it with round($1, 2).

Yeah, perhaps this is not what you expected :)

like image 39
Karolis Avatar answered Oct 18 '22 16:10

Karolis