使用Ruby / Sinatra将字符串格式化为货币

时间:2022-06-07 11:03:17

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.

我在Ruby / Sinatra中有一个应用程序,它使用API​​来返回我需要格式化为货币的字符串,但是没有看到任何简单的方法来执行此操作。

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

具体来说,我想要一个字符串665778打印出$ 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.

我尝试实现Sinatra :: Numeric :: Helpers但是没有用,我怀疑它已经过时了。请指教。在Rails中似乎很容易做但在Sinatra中却没有。

2 个解决方案

#1


1  

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

我想要一个字符串665778打印出$ 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

#2


0  

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

试试这个函数......它在Rails中与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 

#1


1  

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

我想要一个字符串665778打印出$ 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

#2


0  

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

试试这个函数......它在Rails中与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