Friday, August 17, 2018

#1 2005-10-12 06: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

 

#2 2017-12-24 02:17:37 pm

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 4622

Re: How do I round a number to two decimal places?

Note that while julifos's handler is perfectly adequate for many purposes, has the limitation that it only gives the correct results with positive numbers. It also has the feature that it rounds exact half-stages up to the nearest rounding point, like round does when its rounding as taught in school parameter is used and the number's positive.

round works with both positives and negatives. But unless rounding as taught in school, it rounds .5 to the nearest even integer. So .5 may be rounded either up or down, depending on the digit in front of it:

Applescript:

round 75.5 --> 76 (nearest even integer)
round 74.5 --> 74 (nearest even integer)
round 74.5 rounding as taught in school --> 75 (nearest integer away from zero)

round isn't very efficient, though, and the expression 'rounding as taught in school' may not be something you want to see in one of your own scripts.  roll  So if you know the relevant math, using that would be more efficient and possibly more satisfactory.

If you need julifos's handler to work for negatives too, still rounding exact half stages away from zero, this could be a solution:

Applescript:

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

Or to round half stages to the nearest even:

Applescript:

roundThis(-75.545, 2) --> -75.54
on roundThis(n, numDecimals)
   set x to 10 ^ numDecimals
   tell n * x
       if ((it mod 2) ^ 2 > 0.25) then return (it div 0.5 - it div 1) / x
       return it div 1 / x
   end tell
end roundThis


NG

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)