KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method that formats a number as a human-readable bytes value
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: May 31, 2022

The following method is a utility method that format a numeric byte value to a human readable string.

// formatByteDisplay

#DECLARE($byte_r : Real)->$size_t : Text
If (Count parameters=0)
  $byte_r:=0
End if

var $gb_l; $mb_l; $kb_l : Integer
$gb_l:=1024*1024*1024 // GB
$mb_l:=1024*1024 // MB
$kb_l:=1024 // KB

Case of
  : (($byte_r/$gb_l)>=1)
    $size_t:=String(Round($byte_r/$gb_l; 0); "#,##0 GB;-#,##0 GB")
  : (($byte_r/$mb_l)>=1)
    $size_t:=String(Round($byte_r/$mb_l; 0); "#,##0 MB;-#,##0 MB")
  : (($byte_r/$kb_l)>=1)
    $size_t:=String(Round($byte_r/$kb_l; 0); "#,##0 KB;-#,##0 KB")
  Else
    $size_t:=String(Round($byte_r; 0); "#,##0 Bytes;-#,##0 Bytes")
End case

$0:=$size_t


For example:
$v:=formatByteDisplay(1000) // 1,000 Bytes
$v:=formatByteDisplay(100000) // 98 KB
$v:=formatByteDisplay(10000000) // 10 MB
$v:=formatByteDisplay(1000000000) // 954 MB
$v:=formatByteDisplay(100000000000) // 93 GB