View Single Post
Old 08-03-2025, 05:09 PM   #853
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: 12,495
Karma: 8065348
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
Quote:
Originally Posted by Far_Pen_6884 View Post
I'm attempting to display word_count with "K" and "M" suffixes for thousands and millions, respectively. However, I'm encountering an issue saying "TEMPLATE ERROR could not convert string to float". How can I fix the template to work as intended?

Code:
program:
  switch(
    field('#word_count') >= 1000000, format_number(field('#word_count') / 1000000, '{:.1f}') + ' M',
    field('#word_count') >= 1000, format_number(field('#word_count') / 1000, '{:.1f}') + ' K',
    field('#word_count')
  )
The plus sign is not a string concatenation operator. Use & or strcat() instead. Note also that your comparisons won't work because >= is a lexical comparison, not a numeric comparison. Use =>#. The first_matching_cmp() function is more efficient than a series of relational expressions, as is using the short form of field ($lookup_name)

I suggest you read the template language manual.

Example:
Code:
program:
  first_matching_cmp($#word_count,
    1000, $#word_count,
    1000000, format_number($#word_count / 1000, '{:.1f}') & ' K',
    format_number($#word_count / 1000000, '{:.1f}') & ' M'
  )
Quote:
Another question. If I were to ask this on Codidact or StackOverflow, what tags should I use? Should I tag it as `calibre template`, or is there a programming language that uses the same syntax that I should tag instead?
All three of the calibre template languages are specific to calibre. General Program Mode is syntactically similar to Algol68 and is semantically similar to many non-coercing non-object-oriented languages out there.
chaley is offline   Reply With Quote