-3

Is there a method in perl that takes a large number and formats it into postfix characters like 'M', 'K', etc. For example:

number = 9,999,999    output = 10.0M

I can't use things like 'Math::Round' or 'Format::Number' as perl is installed and I cannot install any new modules.

  • 2
    *"I cannot install any new modules."* In case the issue is that you don't have root/admin privileges, [you don't need root to install modules](http://stackoverflow.com/q/3735836). – ThisSuitIsBlackNot Feb 02 '17 at 15:56
  • How precise does it have to be? How many numbers after the decimal have to be displayed? – AntonH Feb 02 '17 at 15:56
  • 1
    Copy code from https://metacpan.org/pod/Number::FormatEng (pure Perl), just as you would copy code from any Answer here. – toolic Feb 02 '17 at 15:57
  • If you can use the code we post here, then you can install modules. If you can't use the code we post here, then what's the point of answering your question? – ikegami Feb 02 '17 at 16:18
  • Sorry, the reason I can't install modules is because I'm running a script over ssh to about 500 servers. I can't install it on each one. So I needed some kind of routine like below which could do it. I would like it to have 2 decimal places, so the answer like '9.54M' is perfect. – user1475463 Feb 02 '17 at 17:51
  • 1
    If you're running the script over SSH, that means you're copying the script to the remote hosts. So just copy any modules you need to the remote hosts, along with your script. – ThisSuitIsBlackNot Feb 02 '17 at 18:12

1 Answers1

0

Basic idea:

$number=9876543;
$NumString = sprintf("%.1f M", int($number/100000 + 0.5)/10);
print "$number   $NumString\n";

OUTPUT: 9876543 9.9 M

Version with a subroutine

sub MegaNumber {
    my($number, $places) = @_;
    $d2 = 10**$places;
    $d1 = 1000000 / $d2;
    $fmt = "%.". $places . "f M";
    sprintf($fmt, int($number/$d1 + 0.5)/$d2);
}

print "9876543 ", MegaNumber(9876543, 1), "\n";
print "9876543 ", MegaNumber(9876543, 2), "\n";
print "987654 ",  MegaNumber(987654,  2), "\n";

Output:

9876543 9.9 M
9876543 9.88 M
987654 0.99 M
G5W
  • 36,531
  • 10
  • 47
  • 80