How to round all the numbers in a region?
elisp, emacs
Solution
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
Problem
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.