I need to work with decimals. In my program, the user need to put a number with decimals to convert that number.
The problem is: If I try to convert the argument into a number I get a integer without decimals.
# ARGV[0] is: 44.33 size = ARGV[0] puts size.to_i # size is: 44 # :(
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.
To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.
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.
You call to_i
, you get integer.
Try calling to_f
, you should get a float.
For more string conversion methods, look here.
If you want more accurate answer with the calculation to avoid bug like this https://www.codecademy.com/en/forum_questions/50fe886f68fc44056f00626c you can use conversion to decimal example :
require 'bigdecimal' require 'bigdecimal/util' size = ARGV[0] size = size.to_d
this should make the printed number become decimal but if you want to make it as float again just put this to_f again
size=size.to_f puts size
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