mirror of
https://github.com/vincentmli/bpfire.git
synced 2026-04-15 13:32:59 +02:00
general-functions.pl: Add formatBytes() function.
This function can be used to convert an amount of bytes to a humand-readable format. For example "3221225472" will become "3MB". Signed-off-by: Stefan Schantl <stefan.schantl@ipfire.org> Signed-off-by: Arne Fitzenreiter <arne_f@ipfire.org>
This commit is contained in:
committed by
Arne Fitzenreiter
parent
6317d55c4a
commit
c5f85b1152
@@ -1261,4 +1261,29 @@ sub get_nameservers () {
|
||||
return &uniq(@nameservers);
|
||||
}
|
||||
|
||||
# Function to format a string containing the amount of bytes to
|
||||
# something human-readable.
|
||||
sub formatBytes {
|
||||
# Private array which contains the units.
|
||||
my @units = qw(B KB MB GB TB PB);
|
||||
|
||||
my $bytes = shift;
|
||||
my $unit;
|
||||
|
||||
# Loop through the array of units.
|
||||
foreach my $element (@units) {
|
||||
# Break loop if the bytes are less than the next unit.
|
||||
last if $bytes < 1024;
|
||||
|
||||
# Divide bytes amount with 1024.
|
||||
$bytes /= 1024;
|
||||
|
||||
# Assign current processed element to unit.
|
||||
$unit = $element;
|
||||
}
|
||||
|
||||
# Return the divided and rounded bytes count and the unit.
|
||||
return sprintf("%.2f %s", $bytes, $unit);
|
||||
}
|
||||
|
||||
1;
|
||||
|
||||
Reference in New Issue
Block a user