Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 625
Steve Avatar asked Sep 23 '26 04:09

Steve


2 Answers

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

like image 120
ck3g Avatar answered Sep 26 '26 03:09

ck3g


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.

like image 35
David Foster Avatar answered Sep 26 '26 03:09

David Foster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!