Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert a decimal point before the last three digits of a number?

Tags:

perl

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

The number is guaranteed to be between 1000 and 999999 (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, for example:

1000   -> 1.000
23513  -> 23.513
999999 -> 999.999

How can I do this?

like image 296
alexwood Avatar asked Aug 19 '09 17:08

alexwood


2 Answers

And yet another way for fun of it ;-)

my $num_3dec = sprintf '%.3f', $num / 1000;
like image 127
draegtun Avatar answered Oct 21 '22 17:10

draegtun


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.

like image 36
Pat Avatar answered Oct 21 '22 16:10

Pat