4

I am having trivial problems converting integer division to a floating point solution in Emacs Lisp 24.5.1.

(message "divide: %2.1f" (float (/ 1 2)))
"divide: 0.0"

I believe this expression is first calculating 1/2, finds it is 0 after truncating, then assigning 0.0 to the float. Obviously, I'm hoping for 0.5. What am I not seeing here? Thanks

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
c3ad-io
  • 115
  • 8

1 Answers1

12

The / function performs a floating-point division if at least one of its argument is a float, and an integer quotient operation (rounded towards 0) if all of its arguments are integers. If you want to perform a floating-point division, make sure that at least one of the arguments is a float.

(message "divide: %2.1f" (/ (float 1) 2))

(or of course if they're constants you can just write (/ 1.0 2) or (/ 1 2.0))

Many programming languages work this way.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • Thank you so much! As long as one of them is a float, the result is a float. I knew that, but learning Lisp had me hypnotized in a way. Thanks – c3ad-io Mar 19 '16 at 13:57
  • 1
    The Elisp manual, node [Arithmetic Operations](http://www.gnu.org/software/emacs/manual/html_node/elisp/Arithmetic-Operations.html), explains this. – Drew Mar 19 '16 at 17:14