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)
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.