in reply to Re^2: Splitting String???
in thread Splitting String???
Truncating is fairly simple:
my $number = 123.1234567; $number =~ s/(?<=\.)(\d{1,6}).*$/$1/; print $number; # 123.123456
=~ s/ indicates that we're going to apply a regex to $number (?<=\.) signifies that the match is to be made after a literal decimal. (\d{1,6}) captures the first six \d characters in the class [0-9], and stores the value in $1. .*$ matches the remainder of the variable contents. / seperates the match from the replacement. $1 is the first six decimal places as captured earlier. /; signifies the end of the regex and line respectively.
If you want to round, that can be done as well (see UPDATE):
$number =~ s/(?<=\.)(\d{1,6})(\d).*$/$2>4?$1+1:$1/e;
$2>4?$1+1:$1 is a ternary conditional, which tests whether the seventh digit should be rounded ($2 > 4), and then returns either $1 + 1 or $1 as appropriate. /e instructs perl to evaluate the replacement as opposed to returning a literal value
UPDATE: The truncation code works; however the rounding code does not. Given that 9 would round to 10, which has the potential to be iterative, eg 9.9999999, it would affect both itself and the preceeding character, which obviously has the ability to affect characters on both sides of the decimal point. Preliminary testing has shown that the correct line is more complex than a simple example. Nevertheless, it remains a decent demonstration of /e.
As it turns out the rounding code is considerably easier than I had originally thought:
my $number = 123.1234567; $number += .0000005; # Add 5 to the seventh digit $number =~ s/(?<=\.)(\d{1,6}).*$/$1/; # truncate to six digits print $number; # 123.123456
It's essentially the same thing as the truncation code above, save the addition of the += line. Adding 5 to the decimal is a fairly common way to round an int -- I guess I just didn't realize it applied to rounding the 7th decimal place as well.
|
|---|