C++ code to Xojo help needed

How to translate ‘decimals’, ‘Math.log’ and ‘parseFloet’ to Xojo code??

function formatBytes(bytes,decimals) { if(bytes == 0) return '0 Byte'; var k = 1000; // or 1024 for binary var dm = decimals + 1 || 3; var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; var i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; }

parseFloat is probably a custom method. I only know the JavaScript method. AFAIK it is not a native C++ function :

Sort of a val().

Math.Log is described here :

It seems Xojo has the same http://documentation.xojo.com/index.php/Log

Math.log is equivalent to Xojo’s log function, i.e., the natural logarithm.
Math.pow is equivalent to Xojo’s exponentiation operator ^. Math.pow(k, i) = k^i
Math.floor is equivalent to Xojo’s floor function

I assume that parsefloat and toFixed are equivalent to the Java & Javascript functions:
toFixed converts the integer part of a numeric value to a string, and parsefloat would convert an entire floating point number to a string.
x.toFixed would be equivalent to str(floor(x)), and parsefloat(x) would be equivalent to str(x)

Works fine except it now uses a fixed decimal of 2:

[code]Function formatBytes(bytes as integer, dm as integer) as string

if bytes = 0 then return “0 Bytes”
dim k as integer = 1000
dim sizes() as string
sizes = array(“Bytes”, “KB”, “MB”, “GB”, “TB”, “PB”, “EB”, “ZB”, “YB”)
dim i as double = floor( log(bytes) / log(k) )
return format(bytes / pow(k , i),"#.00") + " " + sizes(i)

End Function[/code]

Pretty clever code to set the correct suffix. :slight_smile:

yes, but ZB and YB with a fixed base is useless since the max dimension could be uint64 max -> 18.45EB
Btw better use uint64 as type for bytes and if you use a fixed format then drop the dm parameter

Yes, but I’ve always been a bit concerned about using the log function for counting the number of digits in a number, due to the possibility of round off error. Case in point: when I calculate the Log10 of 0.999999999 on my scientific calculator, it returns 1.0 which would give an incorrect result in this algorithm. It’s less of a problem when dealing with integers, but just to be safe, I suggest testing it with example numbers that are all nines. For example:
999
999999
999999999
999999999999
999999999999999
And also numbers ending in a string of zeroes:
1000
1000000
1000000000
1000000000000

These are the sorts of numbers where round off error could lead to incorrect results.