How do I get a number to display to two decimal points?

Hello all!

I have an AppleScript that counts down to a date/time, and returns a text string.

The current result:

"I am fasting for a further 96 hours.”

The desired result:

"I am fasting for a further 96.50 hours.”

Any suggestions/solutions are appreciated.

My current script:

set theDate to (date "Thursday, August 25, 2022 at 7:30:00 pm")
set currentDate to (current date)

set secondsBetweenDates to (theDate - currentDate)
set timeInHours to (secondsBetweenDates div hours)

return ("I am fasting for a further " & (timeInHours as integer) & " hours.")

Here’s one way:

set theDate to (date "Thursday, August 25, 2022 at 7:30:00 PM")
set currentDate to (current date)

set secondsBetweenDates to (theDate - currentDate)
set timeInHours to ((secondsBetweenDates * 100) div hours)

return ("I am fasting for a further " & (timeInHours as integer) / 100 & " hours.")

1 Like

Thank you so much Ed!

There’s no need to coerce to integer as timeInHours is already an integer.

1 Like

True. I didn’t change that part. I don’t think it makes much difference.

1 Like

If you want to get fancy…

set currentDate to (current date)

set timeBetweenDatesInSeconds to (theDate - currentDate)
set daysBetweenDates to timeBetweenDatesInSeconds div days
set hoursMod to (timeBetweenDatesInSeconds mod days)
set hoursBetweenDates to (hoursMod div hours)
set minutesMod to hoursMod mod hours
set minutesBetweenDates to minutesMod div minutes
set secondsBetweenDates to minutesMod mod 60
set verification to secondsBetweenDates + (minutesBetweenDates * minutes) + (hoursBetweenDates * hours) + (daysBetweenDates * days)
set verification to timeBetweenDatesInSeconds - verification
if daysBetweenDates > 0 then
	set dayString to (daysBetweenDates as text) & " days "
else
	set dayString to ""
end if
if hoursBetweenDates > 0 then
	set hourString to (hoursBetweenDates as text) & " hours "
else
	set hourString to ""
end if
if minutesBetweenDates > 0 then
	set minuteString to (minutesBetweenDates as text) & " minutes "
else
	set minuteString to ""
end if
--
if secondsBetweenDates > 0 then
	set secondString to (secondsBetweenDates as text) & " seconds "
else
	set secondString to ""
end if
--
set daysHoursMinutesString to dayString & hourString & minuteString & secondString
1 Like

Very helpful Ed! I will give that a try, as I like the the way the results look!

In these two lines, each occurrence of timeBetweenDatesInSeconds ahould be replaced by secondsBetweenDates.

The math and date libraries include formatting commands.

Edited with that fix, much better, thanks!

I’m curious, I have both installed and use them but I don’t see a better way to do this with those libraries.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.