View Single Post
Old 11-30-2012, 01:39 AM   #2
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 11,731
Karma: 6690881
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
Your problem comes from confusing constants with field (column) values. The string '#chapters' is a constant. It always has the value '#chapters', which as you can see is not a number. To get the value of a metadata field you use the 'field' function. This function takes the name of the field as its first argument. This argument is normally a constant, but certainly does not need to be.

Using the above, your first program would become:
Code:
program:divide(field('#words'), field('#chapters'))
This program can produce floating point output. For that reason you might want to use
Code:
program: format_number(divide(field('#words'), field('#chapters')), '{0:5.0f}')
Finally, if there is any chance that the #chapters field is empty (zero) then you need to test for that before doing the divide. That is more complicated, requiring something like the following:
Code:
program: 
# Get the value of the chapters field so we can use it more easily
chapters = raw_field('#chapters');

# Check if chapters is zero. If it is then put  the empty string into the variable notIsZero
notIsZero = cmp(chapters, 0, 'yes', '', 'yes');

# Ensure that the chapters variable contains a non-zero number. We need this because the divide will happen
# even though we will throw the value away
chapters = test(notIsZero, chapters, '1');

# Return the result of the divide if notIsZero contains the non-empty string, otherwise return the empty string
test(notIsZero,  format_number(divide(field('#words'), chapters), '{0:5.0f}'), '')
chaley is offline   Reply With Quote