Dear Reinhard, X-Air, and WeatherCat scripters,
this topic is dedicated to our famous AppleScripter Edouard.
Can you help me out this problem:
The all new supersonic snow sensor measures in mm (variable x). Is there a possibility to round this variable beneath 5 down and above 5 up? So for example if "x" records 73 the script should tell 70, on the other side if it records 77 it should output 80. The thought behind is that I would not record every millimeter, but only every centimeter.
How can I format the "x" to do this?
This is an old problem that goes all the way back to FORTRAN (at least). The simplest solution is use a trick about how computers convert real numbers into integers. Basically you want to round the number to the next highest power of ten. Here is a solution that assumes you want the output to be literally in cm instead of mm:
set snow_mm to 77
set snow_cm to (snow_mm + 5) / 10 as integer
If you want the result to be 80 instead of 8, multiply the variable
snow_cm by 10 and that will be the answer you are looking for.
The trick is that when you convert a value to an integer it simply drops any decimal that might have been there. When I divide by 10 I convert the number from an integer to a floating point number. Before dividing by 10, I add 5. That shifts everything by effectively 1/2. If the value was 74, it becomes 79. When I divide by 10 it becomes 7.9. However when converting to an integer the floating point is simply dropped, so when it converts 7.9 to an integer it simply becomes 7. On the other hand, suppose the value was 76. Add 5 to get that it becomes 81. Divide by 10 it becomes 8.1. However once again everything after the decimal point is dropped. That leaves you with the 8 cm that you were aiming for.
I hope that's clear. You can paste the code into your script editor and play around with it for yourself.
Cheers, Edouard