[04/19] general-functions.pl: Add formatBytes() function.

Message ID 20200413074550.2735-4-stefan.schantl@ipfire.org
State Accepted
Commit c5f85b115248d828b2f3421e28544b00c2bf419d
Headers
Series [01/19] openvpn: Add WUI page for client usage statistics |

Commit Message

Stefan Schantl April 13, 2020, 7:45 a.m. UTC
  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>
---
 config/cfgroot/general-functions.pl | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
  

Patch

diff --git a/config/cfgroot/general-functions.pl b/config/cfgroot/general-functions.pl
index 41a0eac2d..692e072c2 100644
--- a/config/cfgroot/general-functions.pl
+++ b/config/cfgroot/general-functions.pl
@@ -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;