Convert String to Currency

Hi All,
I have a String and i need to convert it into Currency format and
verify whether it matches to the expected.
Let me explain in detail

String = “$6,178.50 USD / 22,693.01 AED”
I want to split it into 2 different variables like

usa_price = $6,178.50
aed_price = 22,693.01

expected_output= $6,178.50 * 3.67 = 22,693.01 (should match value in
AED)

I tried doing gsub/scan and im confused now, what’s the best way to
achieve this in Ruby!!!

str = “$6,178.50 USD / 22,693.01 AED”

regex = /
\d
[\d,.]*
/xms

str.scan(regex) do |match|
puts match.gsub(’,’, ‘’).to_f + 1
end

–output:–
6179.5
22694.01

On Wed, Oct 10, 2012 at 12:16 AM, ideal one [email protected]
wrote:

expected_output= $6,178.50 * 3.67 = 22,693.01 (should match value in
AED)

How do i do this in Ruby!!!

If you always expect a division here is one way:

irb(main):001:0> s = “$6,178.50 USD / 22,693.01 AED”
=> “$6,178.50 USD / 22,693.01 AED”

irb(main):011:0>
%r{$(\d+(?:,\d+)(?:.\d+)?)\sUSD\s*/\s*(\d+(?:,\d+)(?:.\d+)?)\sAED}
=~ s and p $1, $2
“6,178.50”
“22,693.01”
=> [“6,178.50”, “22,693.01”]

Kind regards

robert

^^ my version:
s="$6,178.50 USD / 22,693.01 AED"
x=s.gsub(’,’,’’).split(/[ a-zA-Z$/]+/).reject{|x| x.empty?}

x is [“6178.50”, “22693.01”]

s = “$6,178.50 USD / 22,693.01 AED”
delta = 100.0 #only good to 3 sig figs due to 3.75
h = Hash[*s.delete($,/).split()].invert
h.each {|k, v| h[k] = v.to_f}
puts h[“US”]
puts h[“AED”]
puts (h[“US”] * 3.67).between?( h[“AED”] - delta, h[“AED”] + delta ) )

6178.5
22693.01
true

Todd

On Wed, Oct 10, 2012 at 7:35 AM, Todd B. [email protected]
wrote:

true
Sorry, supposed to be “USD”, not “US”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs