开发者

Regex multiplication

开发者 https://www.devze.com 2023-02-10 08:11 出处:网络
lo开发者_StackOverflow社区oked around for a while before I asked but I seem to find a lot of how to\'s on email and currency conversion using regex but nothing on just multiplying a number with a set

lo开发者_StackOverflow社区oked around for a while before I asked but I seem to find a lot of how to's on email and currency conversion using regex but nothing on just multiplying a number with a set value. Essentially, I have a currency value field of lets say: 127.25GBP which needs to be converted to 165.42 (only two decimal points and no currency indicator) Can that be done and if yes how?

Your help would be greatly appreciated!

Thanx

Del


Regular expressions are intended for text-matching, not arithmetics. Some of the tools that accept regexes can be used to perform arithmetics, like Perl and Awk for instance.


Regexes, at their core, are intended for matching strings, and in some software libraries for replacing strings with others and similar string processing, but not for doing math. You need to store the value you capture using a regex into a numerical type and do the multiplication on that, then format the result as a string again if needed.

In python 2.7:

import re
exchangeRate = 165.42 / 127.25
numString = re.match('(\d+.\d\d)GBP', '127.25GBP').group(1)
num = float(numString)
numConverted = num * exchangeRate
numConvertedFormatted = "%.2f" % numConverted

If you're doing serious currency calculations, I'd advise for using fixed-point int (or in case of Python decimal) instead of float, though. For approximations float is good enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消