CFLib.org – Common Function Library Project

byteAutoConvert(bytes [, maxreduction])

Last updated March 3, 2010

Version: 0 | Requires: ColdFusion 5 | Library: StrLib

 
Rated 1 time(s). Average Rating: 5.0

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:

view plain print about
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:

view plain print about
<!---
 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>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Tayo Akinmade Tayo Akinmade added
arrayTrim
11 day(s) ago

Will Belden Will Belden added
longTime
17 day(s) ago

James Sleeman James Sleeman added
quickSort
27 day(s) ago

Ben Forta Ben Forta added
GetHostAddress
30 day(s) ago

Top Rated

Darwan Leonardo Sitepu EksporSQLData
Rated 5.0, 16 time(s)

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 13 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson