Steve
Steve

Reputation: 3080

Convert string into Currency format

Using Ruby and Haml, I have a property which is cost. I believe (im new to ruby) that it will be a Float

At the moment the below line outputs my decimal in format like 4.5 instead of 4.50, which is what I want.

%span.value= "£#{event.beers.first.cost)}"

This is my class file for beers.

class Beer
  include Mongoid::Document
  embeds_many :ratings

  field :name, type: String
  field :country, type: Country
  field :cost, type: Float
  field :photos, type: PhotoArray, default: PhotoArray.new
end

Upvotes: 2

Views: 18981

Answers (3)

David Foster
David Foster

Reputation: 669

If you're talking about American currency including:

  • commas every three digits left of the decimal point
  • at most two digits right of the decimal point
  • don't show decimal point if there are zero cents

try this

vals = [123.01, 1234.006, 12, 1234567, 12345678.1,1.001]
vals.map{|num| 
            num.sprintf('%.2f',num)
               .gsub('.00','')
               .reverse
               .scan(/(\d*\.\d{1,3}|\d{1,3})/)
               .join(',')
               .reverse
        }

Which generates the following in a debugger:

=> ["123.01", "1,234.01", "12", "1,234,567", "12,345,678.10", "1"]

It can be tweaked to be useful for some of the European formats by editing the join string, but I don't know much about the European conventions.

Upvotes: 6

ck3g
ck3g

Reputation: 5929

In case you're using Rails you can use number_to_currency helper

Upvotes: 7

Zachary Anker
Zachary Anker

Reputation: 4520

See the string formatting method, the Kernel::sprintf documentation has all of the arguments for it.

In this case, you would want to do %span.value= "%%pound;%.2f" % event.beers.first.cost to get 4.50 rather than 4.5.

Upvotes: 4

Related Questions