Write results of calculations always with two decimal places

23 views
Skip to first unread message

e2o

unread,
Aug 27, 2023, 2:47:05 PM8/27/23
to BBEdit Talk
Hello!

I'm writing an AppleScript to get time values out of text documents in BBEdit. It takes a list of time ranges, totals each line in decimal hours, then adds a grand total.

My times are input in ranges like:

09:30-09:45
11:30-12:00
13:00-14:45
15:15-17:15

And what I want to get out is:

09:30-09:45 0.25
11:30-12:00 0.50
13:00-14:45 1.75
15:15-17:15 2.00 4.50

The script converts the hours and minutes to a single seconds value, then does the subtraction to get the amount of time indicated by the range. I get these times to a decimal hours result  by dividing by 3600. An example looks like this:

set TimeTotalLineCurrent to (TicketTextTimeLineStop - TicketTextTimeLineStart) / 3600

I always want the number of hours to have two decimal places, even with trailing zero(s), but when I add the totals to the lines I get:

09:30-09:45 0.25
11:30-12:00 0.5
13:00-14:45 1.75
15:15-17:15 2.0  4.5

So I don't get the zero after 0.5 or 2.0, or the grand total 4.5

The way the script turns:

this:
09:30-09:45
into this:
09:30-09:45 0.25

is with

```
# Add total time to end of current line in decimal hours
set BBLineNumber to startLine of selection
select insertion point after last character of line BBLineNumber of vDocument
set selection to " " & TimeTotalLineCurrent as text
```

Is there a way to make the text of TimeTotalLineCurrent to always have two decimals?

I'm curious as to why in my sample above the 2.0 gets its zero (but only one), but the 0.5 does not get a trailing zero. I would kind of expect it to just print "2".

I'm also wondering why the 0.25 is getting its leading 0. - but this is exactly how I want it so I'm not complaining.

Thanks for any help!

- eric

e2o

unread,
Aug 27, 2023, 7:56:31 PM8/27/23
to BBEdit Talk
Solved with:

```

# Set TimeRunningTotal to string with 2 decimals

set TimeRunningTotal to TimeRunningTotal as string

set TimeRunningTotal to texts 1 thru (2 + (offset of "." in TimeRunningTotal)) of (TimeRunningTotal & "0")

```


Reply all
Reply to author
Forward
0 new messages