Re: bytes to megabytes
Re: bytes to megabytes
- Subject: Re: bytes to megabytes
- From: email@hidden (Michael Sullivan)
- Date: Mon, 23 Sep 2002 17:10:46 -0400
- Organization: Society for the Incurably Pompous
ken <email@hidden> writes:
>
I was looking in the AS Guidebook for something and stumbled
>
across a piece of code that has me scratching my head. The more
>
I scratch, the less I understand it (and the more hair keeps falling
>
out!)
>
>
--> returns 2 decimal value in megabytes: 774.76
>
tell application "Finder"
>
set this_disk to disk "VST Drive"
>
set free_space to (free space of this_disk) / 1048 / 1000
>
set the whole_value to free_space div 1
>
set the decimal_remainder to (free_space mod 1) * 100 div 1 *
>
0.01
>
set free_space to whole_value + decimal_remainder
>
end tell
>
>
Okay. I understand why they are dividing and then using the
>
div/mod operators. What I don't get is why they used 1048 then
>
1000? Shouldn't it be 1024 and 1024? I really don't get what they
>
did here...
The only think I can think of is that they were trying to save an add
instruction Since 1048000 is just about the right amount under 1048576,
it actually works out to be nearly equivalent to rounding, even though
they truncate.
Also, the following is a faster and more elegant fixed point method.
set free_space_2 to ((free_space * 100 + .5) div 1) / 100
This generalizes to:
on roundfixed(n, places)
return ((n * (10 ^ places) + .5) div 1) / (10 ^ places)
end roundfixed
So I'd rewrite that to:
on freespaceMB_f2(this_disk)
tell application "Finder"
return roundfixed((free space of this_disk) / 1048576, 2)
end tell
end freespace
Or better yet, use Nigel's IEEERound library, which does IEEE rounding,
and (IIRC) takes care of the 12th digit FP problem.
Also, if you want to *display* the fact that there are 2 significant
decimal places, you have to put the whole thing in a string:
on displayfix2(n)
set n to "" & n & "00" -- <snicker>
set {o,text item delimiters} to {text item delimiters, "."}
set listn to text items of n
if count of listn > 2
error "Malformed parameter, displayfix2() requires a number)
end if
set item 2 of listn to text 1 thru 2 of (item 2 of listn)
set nstring to listn as string
set text item delimiters to o
return nstring
end displayfix2
Generalization of this is left as an exercise to the reader.
Michael
--
Michael Sullivan
Business Card Express of CT Thermographers to the Trade
Cheshire, CT email@hidden
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.