I want to limit the decimal places of some of my generated numbers to 2 (i.e. 245.22) so I can display them in a consistent format to the end user.
Is there a simple way to do this?
I want to limit the decimal places of some of my generated numbers to 2 (i.e. 245.22) so I can display them in a consistent format to the end user.
Is there a simple way to do this?
http://www.apple.com/applescript/guidebook/sbrt/pgs/sbrt.08.htm
Round and Truncate
This sub-routine will round and truncate a numeric value and convert it to text. To use, pass the numeric value and the number of desired decimal places as the passed parameters.
NOTE: this sub-routine uses the number_to_text() sub-routine. Be sure to add it to your script as well.
round_truncate(1.04575, 3)
→ “1.046”
on round_truncate(this_number, decimal_places)
if decimal_places is 0 then
set this_number to this_number + 0.5
return number_to_text(this_number div 1)
end if
set the rounding_value to “5”
repeat decimal_places times
set the rounding_value to “0” & the rounding_value
end repeat
set the rounding_value to (“.” & the rounding_value) as number
set this_number to this_number + rounding_value
set the mod_value to “1”
repeat decimal_places - 1 times
set the mod_value to “0” & the mod_value
end repeat
set the mod_value to (“.” & the mod_value) as number
set second_part to (this_number mod 1) div the mod_value
if the length of (the second_part as text) is less than the ¬
decimal_places then
repeat decimal_places - ¬
(the length of (the second_part as text)) times
set second_part to (“0” & second_part) as string
end repeat
end if
set first_part to this_number div 1
set first_part to number_to_text(first_part)
set this_number to (first_part & “.” & second_part)
return this_number
end round_truncate
so, all you have to do is include that somewhere in your script, and then type round_truncate(the_number, decimal_places).
thanks! …wish it could have been simpler though! :shock:
Not simpler but shorter, here is an old handler to do it (not mine):
There are several interpretations to what you ask. Do you just want to truncate after the second decimal place? Do you want to round to the nearest hundredth? If rounding, do you want to round .005 away from zero or to the nearest even? If the second decimal place is a zero, do you want to display it?
You might like to rummage through my rounding handlers, which are here in ScriptBuilders.
truncating will be just fine for what I need …thanks everyone!