chadp
chadp

Reputation: 135

Convert Integer to Float in Elisp

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

Upvotes: 4

Views: 2151

Answers (1)

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.

Upvotes: 12

Related Questions