nohayeye
nohayeye

Reputation: 2024

Convert Yen to Float in Ruby

I have a string that looks like this: "¥3,250". I want to convert it into a float.

I already tried something like this:

    price = "¥3,250"
    price[0] = ""
    price.to_f

but ruby uses the comma (,) as a decimal seperator.

Upvotes: 0

Views: 66

Answers (3)

fmendez
fmendez

Reputation: 7338

You could try this:

   price = "¥3,250"
   price.gsub(/[,|¥]/,'').to_f   #=> 3250.0

Upvotes: 0

sawa
sawa

Reputation: 168091

price = "¥3,250"
price.delete("¥,").to_f

Upvotes: 0

Anthony Alberto
Anthony Alberto

Reputation: 10395

price_as_float = price.scan(/\d|\./).join('').to_f

It should work even with, say "¥3,250.4"

All it does is extract digits and dots from the string and creates a string from it, then casting it to a float

Upvotes: 2

Related Questions