-1

I have an app in Ruby/Sinatra that uses an API to return a string that I need to format as currency but don't see any simple way to do this.

Specifically, I'd like a string 665778 to print out as $665,778

I tried implementing Sinatra::Numeric::Helpers but that didn't work and I suspect it's outdated. Please advise. There seems easy to do in Rails but not in Sinatra.

peacecoder
  • 93
  • 1
  • 13
  • Possible duplicate of [What is the best method of handling currency/money?](http://stackoverflow.com/questions/1019939/what-is-the-best-method-of-handling-currency-money) – osman Feb 22 '16 at 18:54
  • 2
    @osman not a duplicate because that answer is for rails. i'm using sinatra. the issue seems easier to handle in rails. – peacecoder Feb 22 '16 at 19:01
  • 1
    Your question isn't clear. "format as currency" can mean a lot of different things. What is your expected result? `1234.56`? `£1,234.56`? `€ 1.234,56`? Something else? – Jordan Running Feb 22 '16 at 19:10
  • @Jordan I clarified above. Thank you. – peacecoder Feb 23 '16 at 03:34

2 Answers2

3

I'd like a string 665778 to print out as $665,778

Borrowing the thousands-grouping code from this answer yields a succinct solution:

def number_to_currency(num)
  "$#{num.to_s.gsub(/\d(?=(...)+$)/, '\0,')}"
end
Community
  • 1
  • 1
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
0

Try this function ... it's equivalent in Rails to number_to_currency:

def to_cash(unit = "R$",separator = ",",delimiter = ".")
    mystring = sprintf("%s %.2f",unit, self)
    mystring = mystring.gsub(".",separator)
    pos = mystring.match(separator).begin(0) - 3
    while !(/[0-9]/.match(mystring[pos])== nil) do
        mystring.insert(pos,delimiter)
        pos-=3
    end 
    return mystring
end 
Leonardo Ostan
  • 180
  • 1
  • 6