Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to decimal number in ruby

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 # :( 
like image 727
ElektroStudios Avatar asked Mar 31 '12 14:03

ElektroStudios


People also ask

How do you convert string to decimal in Ruby?

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 convert a string to an integer in Ruby?

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.

How do you get a decimal 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.


2 Answers

You call to_i, you get integer.

Try calling to_f, you should get a float.

For more string conversion methods, look here.

like image 187
Sergio Tulentsev Avatar answered Sep 17 '22 11:09

Sergio Tulentsev


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 
like image 23
Tau-fan Ar-if Avatar answered Sep 18 '22 11:09

Tau-fan Ar-if