Extract number (float) from string

Hi Please advice how to extract exact number from string:

$5.99 /LB

I need to get 5.99 as float number

Thank you in advance

On 12/05/2012 07:31 AM, Alexander G. wrote:

Hi Please advice how to extract exact number from string:

$5.99 /LB

I need to get 5.99 as float number

Thank you in advance

How about;

irb
1.9.3p125 :001 > s = ‘$5.99 /LB’
=> “$5.99 /LB”
1.9.3p125 :002 > s.match(/^$(\d+.\d+).*$/)[1].to_f
=> 5.99

You may want to split it into steps and do some error checking, or just
wrap it in a rescue, depending on where your input comes from and where
your output is going.

Sam

Sam D. wrote in post #1087818:

On 12/05/2012 07:31 AM, Alexander G. wrote:

Hi Please advice how to extract exact number from string:

$5.99 /LB

I need to get 5.99 as float number

Thank you in advance

How about;

irb
1.9.3p125 :001 > s = ‘$5.99 /LB’
=> “$5.99 /LB”
1.9.3p125 :002 > s.match(/^$(\d+.\d+).*$/)[1].to_f
=> 5.99

You may want to split it into steps and do some error checking, or just
wrap it in a rescue, depending on where your input comes from and where
your output is going.

Sam

Sorry didn’t work for me.
That’s what it returns: $5.99 /LB
still the same

prices = [
‘$ 5.99/LB’,
‘$5.99 /LB’,
‘5.99 / lb’,
‘0.99 / lb’,
‘.99/lb’
]

results = prices.map do |str|
str.match(/[.\d]+/)[0].to_f
end

p results

–output:–
[5.99, 5.99, 5.99, 0.99, 0.99]

On Wed, Dec 5, 2012 at 2:31 AM, Alexander G. [email protected]
wrote:

how to extract exact number from string:
$5.99 /LB
need to get 5.99 as float number

see ri String#slice

eg,

“$5.99 /LB”[/[\d.]+/].to_f
=> 5.99

best regards -botp

Am 04.12.2012 21:00, schrieb [email protected]:

Using float for currency is a bad idea.

[13] pry(main)> 1.11 - 0.12
=> 0.9900000000000001

/$(?\d+).(?\d+)/ =~ “$5.99 /LB”
amount_in_cent = 100 * dollars.to_i + cents.to_i # => 599

(see RegExp documentation)

Am 04.12.2012 19:31, schrieb Alexander G.:

Hi Please advice how to extract exact number from string:

$5.99 /LB

I need to get 5.99 as float number

Thank you in advance

Using float for currency is a bad idea.

[13] pry(main)> 1.11 - 0.12
=> 0.9900000000000001

On Tue, Dec 4, 2012 at 1:50 PM, 7stud – [email protected] wrote:

str.match(/[.\d]+/)[0].to_f

Interestingly, this works because of the way to_f interprets such things
as:

“…”.to_f # => 0.0
“.0.0.0.0.0.”.to_f # => 0.0

both of which will also be caught by the regexp.

I can’t figure out how to unsubscribe. Help!

Joanne

On Tue, Dec 4, 2012 at 9:01 PM, botp [email protected] wrote:

“$5.99 /LB”[/[\d.]+/].to_f
=> 5.99

That’s a quite lazy match which will also try to convert “…” into a
float. We can do more specific:

irb(main):002:0> “$5.99 /LB”[/\d+.\d+/].to_f
=> 5.99

Or, more thoroughly:

irb(main):004:0> “$5.99 /LB”[/[-+]?\d+(?:.\d+)?/].to_f
=> 5.99

But I agree with sto.mar that storing currency values in a float is a
bad idea.

Kind regards

robert