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:
...in roughly that order.
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.
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.
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.
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.
(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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With