user3437721
user3437721

Reputation: 2289

regex to pull in number with decimal or comma

This is my line of code:

col_value = line_item[column].scan(/\d+./).join().to_i

When I enter 30,000 into the textfield, col_value is 30. I want it to bring in any number: 30,000 30.5 30.55 30000

Any of these are valid...

Is there a problem with the scan and or join which would cause it to return 30? Using the suggested regexes below still retunrs 30 e.g.

col_value = line_item[column].scan(/\d+[,.]?\d+/).join().to_i

Could it be that "to_i" converts "30,000" to 30??

Upvotes: 1

Views: 626

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Yes, "30,000".to_i #=> 30". See String#to_i: "Extraneous characters past the end of a valid number are ignored."

I suggest you first remove the commas, then apply a regex:

R = /
    \d+      # match >= 0 digits
    |        # or
    \d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
    /x       # extended mode

str = "30,000 30.5 30.55 30000 1. .1"
str1 = str.tr(',','')
  #=> "30000 30.5 30.55 30000 1. .1" 
a = str1.scan(R)
  #=> ["30000", "30", "5", "30", "55", "30000"] 
a.map(&:to_i)
  #=> [30000, 30, 5, 30, 55, 30000] 

After chaining, we have:

str.tr(',','').scan(R).map(&:to_i)

If the desired solution is instead:

  #=> [30000, 30, 5, 30, 55, 30000, 1, 0]

the regex needs to be modified as follows:

R = /
    \d+      # match >= 0 digits
    |        # or
    \d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
    |        # or
    \d+\.    # match > 0 digits, then a decimal point
    |        # or
    \.\d+    # match a decimal point, then > 0 digits
    /x       # extended mode

Upvotes: 0

vks
vks

Reputation: 67968

\d+(?:[,.]\d+)?

Try this.This should do it for you.

Upvotes: 1

Rahul
Rahul

Reputation: 3509

This regex will match you desired output:

\d+[,.]?\d*

here ? is used as optional to match.

DEMO

Upvotes: 1

Related Questions