tags:

views:

452

answers:

4

I have a number, and need to add a decimal to it for formatting.

The number is guaranteed to be between 999999 and 1000 (I have covered the other possibilities in other ways, this is the one I can't get my head around). I need to put a decimal before the last 3 digits, such as:

999.999 or 1.000 or 23.513

What kind of regex will accomplish this?

+7  A: 
$num =~ s/(\d{3})$/.$1/

That says: Take a block of 3 digits (that must be anchored at the END of the string) and replace them with a "." followed by whatever was just matched.

Adam Batkin
This is not the best answer; see below for draegtun's response which is preferable.
Ether
Actually it *is* the best answer to the question that was asked, though possibly not the best way to accomplish the task at hand. The question specifically asked for a regular expression.
Adam Batkin
+11  A: 

Here is another solution just for the fun of it:

In Perl substr() can be an lvalue which can help in your case.

substr ($num , -3 , 0) = '.';

will add a dot before the last three digits.

You can also use the four arguments version of substr (as pointed in the comments) to get the same effect:

substr( $num, -3, 0, '.' );

I would hope it is more elegant / readable than the regexp solution, but I am sure it will throw off anyone not used to substr() being used as an lvalue.

Pat
That's a very cool solution!
Adam Batkin
Better written as "`substr( $num, -3, 0, '.' );`"
Brad Gilbert
That is amazing!
Axeman
Yep! See also: http://stackoverflow.com/questions/505028/how-do-i-place-a-colon-into-a-string-two-characters-from-the-end-using-perl/505279#505279
draegtun
+19  A: 

And yet another way for fun of it ;-)

my $num_3dec = sprintf '%.3f', $num / 1000;

/I3az/

draegtun
I think that this too clearly expresses the meaning of the input data, and should be avoided in favor of something more mysterious :-)
Roboprog
+1 This is the right answer to the question. The fact that the OP mistakenly believed a regex substitution was needed does not change that.
Sinan Ünür
No, this isn't necessarily *the* right answer to the question. If you have a 64bit perl and >15 digit numbers, this may well be the wrong answer, while the substr or s/// will always work.
ysth
@ysth: Yes but question was limited to 1000 - 999999 (integers) so it is actually "the right answer" ;-)
draegtun
It's the right answer if that's what you want to do!
Chris Huang-Leaver
Correct. Especially has the re -)
draegtun
TMTOWTFIU.
chaos
"TMTOWTFIU"??? Love it, ha ha!
Roboprog
A: 

Golf anyone?

substr $num,-3,0,'.';
zakovyrya