I’m trying to find a way to convert decimals to fractions automatically within a document. We pull in a page of information for a publication that has decimals which must be converted to fractions. Is there a way of doing this with a script? Thanks for anyone’s help!
Here’s one I wrote a while ago that does something similar; I think the key math is in there. I bet it can be done much more efficiently, but here ya go. You’ll need to change it to return something using my variable outputText (mine returns a decimal adjusted to the nearest 1/32, i.e. .06 returns .0625, etc.):
roundFractionalInch(text returned of (display dialog "" default answer ""))
on roundFractionalInch(givenNum)
set givenInteger to givenNum div 1
set givenFraction to givenNum mod 1
set denominator to 32
set numerator to round (givenFraction * denominator)
set nearestFraction to numerator / denominator
if (nearestFraction ≠givenFraction) then
repeat 5 times --cut it evenly in half as many times as you can:
if numerator div 2 ≠numerator / 2 then exit repeat
set numerator to (numerator / 2) as integer
set denominator to denominator div 2
end repeat
end if
set outputText to ""
if givenInteger > 0 then set outputText to (givenInteger as text)
if givenInteger > 0 and numerator > 0 then set outputText to (givenInteger as text) & " and "
if numerator > 0 then set outputText to outputText & numerator & "/" & denominator
if givenNum as real ≠(givenInteger + nearestFraction) then
display dialog "The value is " & givenNum & "\"." & return & "Shall we adjust that”perhaps to " & outputText & ¬
"\"?" default answer (givenInteger + nearestFraction) buttons {"Don't Adjust", "Adjust"} default button 2
if button returned of the result is "Adjust" then
return text returned of the result
else
return givenNum
end if
else
return givenNum
end if
end roundFractionalInch