Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 243
c3ad-io Avatar asked Dec 15 '22 07:12

c3ad-io


1 Answers

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.

like image 130
Gilles 'SO- stop being evil' Avatar answered Jan 03 '23 11:01

Gilles 'SO- stop being evil'