使用正则表达式四舍五入 [英] Rounding using regular expressions

查看:517
本文介绍了使用正则表达式四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用正则表达式对数字进行舍入?问题是我在文件中有很多数字到小数点后两位以上,我需要将它们移动到小数点后两位。

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.

它在源代码中因此,理想情况下,我希望使用Visual Studio的查找和替换文件,但是如果正则表达式没有答案,我不反对编写脚本在文件上运行(将其作为纯文本格式)的想法。

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.

推荐答案

您不能仅使用正则表达式来做到这一点,正如Ryan指出的那样,但是您可以使用正则表达式在输入中查找小数并在替换操作上使用回调函数。

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.

在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.

这篇关于使用正则表达式四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆