help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to read an integer from the minibuffer


From: Emanuel Berg
Subject: Re: How to read an integer from the minibuffer
Date: Tue, 16 Nov 2021 12:37:36 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/29.0.50 (gnu/linux)

Yuri Khan wrote:

> If you’re checking the input string by regexp anyway, you could do
> that before calling the parser and simplify to:
>
>     (defun string-to-number-strict (str)
>       (if (string-match
> "^[+-]?\\([[:digit:]]+\\|[[:digit:]]*\\.[[:digit:]]+\\)$" s)
>           (string-to-number s)
>         (error "invalid number")))
>
> Depending on circumstances, you might want to refine the
> regexp to disallow leading zeros unless it is the only digit
> in the integer part; and/or allow exponential format.

Okay, so now we are getting somewhere ... I love the
question mark.

As for disallowing leading zeroes I think it should be as
close to Emacs as possible, eval 00 for example.

(defun string-to-number-number (str)
  (let ((s (string-trim str)))
    (when (string-match
           "^[+-]?\\([[:digit:]]+\\|[[:digit:]]*\\.[[:digit:]]+\\)$" s)
      (string-to-number s) )))

;; (string-to-number-number " 10")                  ;  10
;; (string-to-number-number "  1.5")                ;   1.5
;; (string-to-number-number " +0")                  ;   0
;; (string-to-number-number "  0")                  ;   0
;; (string-to-number-number " -0.0")                ;  -0.0
;; (string-to-number-number " -1.5")                ;   1.5
;; (string-to-number-number "-10")                  ; -10
;; (string-to-number-number "123this used to work") ; nil
;; (string-to-number-number "NAN")                  ; nil

> It might also be a good idea to wrap all that in
> a ‘save-match-data’.)

What/how do you mean?

-- 
underground experts united
https://dataswamp.org/~incal




reply via email to

[Prev in Thread] Current Thread [Next in Thread]