@badkins do you want that feature because you’re doing stuff with amounts of currency?
@notjack yes, I need to display currency values
Rails does it like this: def parts
left, right = number.to_s.split('.')
left.gsub!(DELIMITED_REGEX) do \|digit_to_delimit\|
"#{digit_to_delimit}#{options[:delimiter]}"
end
[left, right].compact
end
and then joins again with a .
I originally had something more functional, but likely very inefficient: (define (number->currency n)
(define (commatize str)
(~> str
(string->list _)
(reverse _)
(chunk _ 3)
(map list->string _)
(string-join _ ",")
(string->list _)
(reverse _)
(list->string _)))
(let* ([ str (~r n #:precision (list '= 2)) ]
[ pair (string-split str ".") ]
[ whole (first pair) ]
[ fractional (second pair) ])
(string-append "$" (commatize whole) "." fractional)))
so I’ll probably use the regex replace approach
… even though it feels dirty :slightly_smiling_face:
@badkins Would it help if there was a money?
type? Such a type could 1) provide formatting functions, 2) do exact decimal math instead of IEEE math, 3) have a nice printed representation at the REPL, 4) make it easier to avoid getting your units mixed up
Possibly. It’s easy enough to just use an integer for cents, but the formatting is important. Racket’s handling of exact numbers helps.
I think Neil has implemented fixed point numbers somewhere.
there’s probably tons of localization stuff relevant to this too
Yeah, that’s what the racket-locale
was supposed to handle I think, but it dropped the ball on formatting, and shook my confidence in the code in general.
Huh, never realized racket-locale
existed before
I’ll just work out a very efficient commatization, and that will probably be all I need. Rails had a money library, but in the end, it was just easier to use cents.
There is also the cldr
libraries which address some of the locale stuff, but I think it was mostly to serve gregor
s uses.
So I don’t know if it fully handles number. It does ok with times.
Has a bug, e.g. -123
=> $-,123.00
After trying a few implementations, benchmarking & fixing bugs, here’s what I came up with. The regex replace method turned out to be too slow.
I’m really glad I added the random test because it immediately exposed a stupid bug involving embedded zeros.
Takes about 4 μs, so fast enough for my purposes.