(pretty-int)

Started by alex, March 29, 2006, 09:31:16 AM

Previous topic - Next topic

alex

(pretty-int)

I wrote useful function(IMHO)
;; Transform integer to special string format(see example)
;;
;; syntax: (pretty-int num)
;; syntax: (pretty-int num delimiter)
;;
;; Example:
;;   (pretty-int 20482048) -> "20 482 048"
;;   (pretty-int 1234567890 "'") -> "1'234'567'890"
;;
(define (pretty-int num delimiter)
  (unless delimiter (setq delimiter " "))
  (trim (reverse (replace {(d{3})} (reverse (string num)) (append $1 delimiter) 0)) delimiter)
)
Can anybody propose more simple or useful variant?

Sammo

#1
Hello Alex,



Nice work. Here's another solution that uses a regular expression I found in RegexBuddy's (http://www.regexbuddy.com/">//http://www.regexbuddy.com/) library.
(define (pretty-int num delim)
  (let
    ( pattern "(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" )
  ;body of let
    (replace pattern (string num) (or delim " ") 0) ))

Dmi

#2
I usins such one:
(define (format-sum a)
  (let (s (format "%18.2f" a) r "")
    (dotimes (i 5)
      (set 'r (append r " " ((* 3 i) 3 s))))
    (append r (-3 s))))

not much elegant, but quite nice for finacial reports...
WBR, Dmi