Re: Number of Decimal Places
Re: Number of Decimal Places
- Subject: Re: Number of Decimal Places
- From: email@hidden (Michael Sullivan)
- Date: Mon, 22 Apr 2002 17:24:57 -0400
- Organization: Society for the Incurably Pompous
>
Hi. Here is an open challenge:
>
>
I would like to, in the fewest lines of code, determine the number of
>
decimal places of a "real" named x.
>
For instance, "1" would be 0, "1.1" would be 2, "1.11" would be 3, etc.
>
Using the following guide, I'd like to know who can come up with the
>
fewest lines of code to return the correct number of decimal places:
>
--Use this code:
>
set x to (the text returned of (display dialog "Number:" default
>
answer "")) as real
>
--Code
>
display dialog "The number of decimal places of " & x & " is " &
>
decimalplaces
Just your luck, I've been doing a bunch of math crap lately.
How's this handler. I could obfuscate it some more to make it smaller,
but I'd prefer to do things that would add code, like check for the
infamous 12th place precision error, and such. BTW, the limitations of
applescripts conversion from number to string make the response look
wrong in a couple spots, but my algorithm is giving the correct answer
(the conversion is cropping places that Applescripts FP can hold)
There's also the question of whether you really want decimal places.
Since you wanted to count the 1, I'm assuming you're really looking for
precision, so I also dropped anything that's trailing zeros.
For instance, if you type in 100000, you'll get 1. That might not
really be the best answer now that I think of it, and there's not really
anyway to tell whether your trailing zeros represent precision or not...
That can be gotten rid of easily enough and it makes the code even
shorter. See Precision2(n)
--begin script
(*
* Precision
* by Michael E. Sullivan
*
* copyright 4/22/2002
* open source freeware to be used or edited freely with credit
*
*)
set x to (the text returned of (display dialog "Number:" default
[NO BREAK]answer "")) as real
display dialog "The number of decimal places of " & x & " is " &
[NO BREAK]Precision(x)
on Precision(n)
repeat with j from 0 to 999
if ((n / (10 ^ j)) < 1) then exit repeat
end repeat
repeat with k from j to 0 by -1
if (n / (10 ^ k)) = ((n / (10 ^ k)) div 1) then exit repeat
end repeat
repeat with i from 0 to 16
if (n * (10 ^ i)) = ((n * (10 ^ i)) div 1) then return i + j - k
end repeat
end Precision
on Precision2(n)
repeat with j from 0 to 99
if ((n / (10 ^ j)) < 1) then exit repeat
end repeat
repeat with i from 0 to 16
if (n * (10 ^ i)) = ((n * (10 ^ i)) div 1) then return i + j
end repeat
end Precision2
-- end script
--
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.