Friday, December 15, 2017

#1 2005-10-12 07:27:25 am

julifos
Administrator
From:: Malasaña, Madrid
Registered: 2002-11-20
Posts: 2014

How do I round a number to two decimal places?

AppleScript's "round" command works only to round a number to its nearest integer, for example:

Applescript:

round (75.6) --> 76

But how would you round, say 76.5436 to 76.54? Since the round command always produces an integer, you first multiply the real number by 100, round it, then divide by 100. For example:

Applescript:

(round (75.5436 * 100)) / 100 --> 75.54

Similarly, to get three decimal places you would use 1000:

Applescript:

(round (75.5436 * 1000)) / 1000 --> 75.544

You can also use this common routine:

Applescript:

roundThis(75.5436, 1) --> 75.5
on roundThis(n, numDecimals)
   set x to 10 ^ numDecimals
   (((n * x) + 0.5) div 1) / x
end roundThis

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)