CFLib.org – Common Function Library Project

byteAutoConvert(bytes[, maxreduction])

Last updated March 03, 2010

author

Joerg Zimmer

Version: 0 | Requires: CF5 | Library: StrLib

Description:
pass this function your byte-vales (for example from a cfdirectory-resultset) and receive the value converted to the shortest possible, human-readable format. It's possible to limit the amount of reduction.

Return Values:
returns a string

Example:

Autoconvert: #byteAutoConvert(1124008800)#<br />
Convert to MB or lower: #byteAutoConvert(1124008800,2)#

Parameters:

Name Description Required
bytes size in bytes to format Yes
maxreduction limit on reduction No

Full UDF Source:

<!---
 Converts Byte values to the shortest human-readable format
 03-mar-2010 minor change to the way units variable was created
 
 @param bytes      size in bytes to format (Required)
 @param maxreduction      limit on reduction (Optional)
 @return returns a string 
 @author Joerg Zimmer (joerg@zimmer-se.de) 
 @version 0, March 3, 2010 
--->
<cffunction name="byteAutoConvert" access="public" returntype="string" output="false">
    <cfargument name="bytes" type="numeric" required="true">
    <cfargument name="maxreduction" type="numeric" required="false" default="9">
    <cfset var units = listToArray("B,KB,MB,GB,TB,PB,EB,ZB,YB",",")>> 
    <cfset var conv = 0>
    <cfset var exp = 0>
    
    <cfif arguments.maxreduction gte 9>
        <cfset arguments.maxreduction = arraylen(units) - 1>
    </cfif>
    
    <cfif arguments.bytes gt 0>
        <cfset exp = fix(log(arguments.bytes) / log(1024))>
        <cfif exp gt arguments.maxreduction>
            <cfset exp = arguments.maxreduction>
        </cfif>
        <cfset conv = arguments.bytes / (1024^exp)>
    </cfif>
            
    <cfreturn "#trim(lsnumberformat(conv,"_____.00"))# #units[exp + 1]#"/>
</cffunction>

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson