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?
And yet another way for fun of it ;-)
my $num_3dec = sprintf '%.3f', $num / 1000;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With