Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a decimal value from a String in Ruby

I have a Ruby String that contains decimal-containing numbers. What's the best way to convert this into a decimal (fixed-point)?

"Best" means:

  • Reliable given a wide range of input options
  • Simple to write
  • Easy to read
  • DRY

...in roughly that order.

like image 302
Craig Walker Avatar asked Jan 30 '10 21:01

Craig Walker


People also ask

How do I extract numbers from a string in Ruby?

extract numbers from a string : scan « String « Ruby uses \d to match any digit, and the + that follows \d makes \d match as many digits in a row as possible. scan through all the vowels in a string: [aeiou] means "match any of a, e, i, o, or u." Just like /\w+/, but doesn't consider underscore part of a word.

How do you convert a string to a decimal 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.

How do you get decimals in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.

How do you convert a string to a decimal?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent. When a value is returned by this method, the conversion was successful.


1 Answers

(Found it myself after a bit of digging)

BigDecimal is the standard Ruby fixed-point type, and it's constructor takes a String and handles the parsing for you:

BigDecimal.new("123.45")
like image 177
Craig Walker Avatar answered Oct 06 '22 00:10

Craig Walker