Rounding numbers to N decimals in Emacs
I have recently faced a problem, where I had a bunch of SVG files with a large amount of fraction numbers in the path definitions. These images were displayed in small size, so this amount of precision was irrelevant, and these numbers took almost half of my SVG images’ size. So I created an Elisp defun to round these numbers to 2 decimals:
defun get-number-at-point () ( (interactive)"0123456789.-") (skip-chars-backward or (looking-at "[0123456789.-]+") (error "No number at point")) (0))) (string-to-number (match-string defun round-number-at-point-to-decimals (decimal-count) ("NDecimal count: ") (interactive let ((mult (expt 10 decimal-count))) ( (replace-match (number-to-string/ (fround (* ( mult (get-number-at-point))) mult)))))
This finds the first digit of the number under point (the cursor), and reduces its digits to the given amount (or the number given with
C-u). It has some drawbacks, though, as it cannot handle exponential forms (e.g.
1e-1234), but these were rare in my case, and its hard to iterate through all numbers. I will come over this latter problem soon(ish).