Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round all the numbers in a region?

Tags:

emacs

elisp

I am editing a latex file, and there are too many decimal places in one of my tables. If I want to round all the numbers in a table (or a region) to tenths or hundredths, what can I do?

I googled and found some lisp functions, like

(format "%0.2f" 1.2345)
(round 1.2)

etc, but I do not know how to apply them to all the numbers in a region. Thanks.

like image 696
liuminzhao Avatar asked Dec 05 '22 06:12

liuminzhao


2 Answers

You can perform this task without having to write a dedicated Elisp function, using query-replace-regexp interactively:

C-M-%[0-9]+\.[0-9]+RET\,(format "%0.2f" \#&)RET

The \,(...) in the replacement text means to interpolate the result of calling the parenthesized Lisp expression, and \#& means "whatever the entire pattern matched, converted to a number."

like image 66
Sean Avatar answered Dec 21 '22 08:12

Sean


For me that's a common use case: search something in the region and do something with the matched text.

So there's a useful code snippet here: http://wikemacs.org/wiki/Emacs_Lisp_Cookbook#Scripted_Use

I just had to convert the matched string to an int with string-to-number.

Adapt my regexp to your needs.

That't the function I ended up with:

(defun my-round-nb (start end)
"round the nb of the region."
(interactive "r")
(save-restriction
  (narrow-to-region start end)
  (goto-char 1)
  (let ((case-fold-search nil))
    (while (search-forward-regexp "\\([0-9]+\\.[0-9]+\\)" nil t)
      (replace-match (format "%0.2f" (string-to-number (match-string 1)))
                   )))))

my doc: http://wikemacs.org/wiki/Category:Emacs_Lisp

like image 33
Ehvince Avatar answered Dec 21 '22 09:12

Ehvince