質問

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.

役に立ちましたか?

解決 2

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

他のヒント

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."

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top