Keep three decimal places and throw the third if it's "0"

8/10/2017 posted in  编程 comments

For example:

14.98812 -> 14.988
1.8731312 -> 1.873
2.33045 -> 2.33

script in perl:

$price =~ s/(\.\d\d[1-9]?)\d*/$1/

Explain:

\.matches the point

\d\d matches the first two digits
[1-9]? matches the third digit if it's between 1 to 9

match all above as a group, in perl, can use $1 to identical the group first

\d* to match all the rest digits if exists.

at last, replace the matched string(e.g. 1.231323131) and replace with the first matched group(the 3 useful digits if the third one is not 0).