rnso
rnso

Reputation: 24545

Easy function to commatize a number in string in Racket

To add commas to a number in string, can there be a simple function for common situation use? I found one method but it seems very complex though comprehensive: https://rosettacode.org/wiki/Commatizing_numbers#Racket

I simply want to have a function which works as follows:

(addcommas 1234567890)
"1,234,567,890"

(It is slightly surprising that Racket, which has many high level functions, does not have a built-in function for this common requirement).

Upvotes: 1

Views: 161

Answers (1)

Renzo
Renzo

Reputation: 27424

You can try with this:

(define (addcommas n)
  (define (split n acc)
    (if (< (abs n) 1000)
        (cons n acc)
        (let-values ([(quot rem) (quotient/remainder n 1000)])
          (split quot (cons (abs rem) acc)))))
  (apply ~a (split n '()) #:separator ","))

(addcommas -2332342390)

;; -> "-2,332,342,390"

If you want to format real numbers, since they have a binary representation, and the conversion can be imprecise, you have to add a precision parameter which specifies the number of digits after the point:

(define (addcommas-real n precision)
  (let* ((int-part (exact-truncate n))
         (float-part (exact-truncate (* (-  n int-part) (expt 10 precision)))))
    (~a (addcommas int-part) "." (abs float-part))))

(addcommas-real -2332342390.34 2)

;; -> "-2,332,342,390.34"

(addcommas-real -2332342390.34 5)

;; -> "-2,332,342,390.34000"

Upvotes: 2

Related Questions