Convert string into Currency format

17,306

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
17,306
Steve
Author by

Steve

Updated on June 05, 2022

Comments

  • Steve
    Steve about 2 years

    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
    
  • Steve
    Steve over 12 years
    thanks, the line of code I ended up using was "£#{"%.2f" % event.beers.first.cost}"