(pretty-int)

For the Compleat Fan
Locked
alex
Posts: 100
Joined: Thu Mar 10, 2005 2:27 pm
Location: Russia

(pretty-int)

Post by alex »

(pretty-int)
I wrote useful function(IMHO)

Code: Select all

;; 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
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

Hello Alex,

Nice work. Here's another solution that uses a regular expression I found in RegexBuddy's (http://www.regexbuddy.com/) library.

Code: Select all

(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
Posts: 408
Joined: Sat Jun 04, 2005 4:16 pm
Location: Russia
Contact:

Post by Dmi »

I usins such one:

Code: Select all

(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

Locked