Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string with USD "money" converted to number

Tags:

Is there currently a gem that's capable of taking strings, all in USD for this purpose, and converting them to a number? Some examples would be:

  • "$7,600" would turn into 7600
  • "5500" would turn into 5500

I know on the "5500" example I can just do "5500".to_i, but the spreadsheets being imported aren't consistent and some include commas and dollar signs while others do not. There a decent way of handling this across the board in Ruby?

I've tried something like money_string.scan(/\d/).join which seems to be fine, just worried I'll run into edge cases I haven't found yet, such as decimal places.

like image 447
randombits Avatar asked Dec 10 '13 01:12

randombits


People also ask

How do I convert a string to a number in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

What is Ruby money?

Ruby Currency is an ERC 20 token that runs on the Ethereum blockchain and has a similar function to Bitcoin, Ethereum, Bitcoin Cash, and other cryptocurrencies. Ruby Currency is a multi-asset blockchain-based cryptocurrency that aims to allow traders to trade a wide range of products such as BTC, ETH, Ripple, and more.


1 Answers

Why not remove all non-digit characters before calling .to_i

Example:

"$7,600".gsub(/\D/,'').to_i 

And for a floating point number:

"$7,600.90".gsub(/[^\d\.]/, '').to_f 
like image 98
naikipl Avatar answered Oct 03 '22 12:10

naikipl