Convert string to decimal in ruby

I need to work with decimals. In my program, the user needs to put a number with decimal places to convert this number.

Problem: if I try to convert the argument to a number, I get an integer without decimals.

# ARGV[0] is: 44.33 size = ARGV[0] puts size.to_i # size is: 44 # :( 
+44
decimal ruby numbers
Mar 31 2018-12-12T00:
source share
4 answers

You call to_i , you get an integer.

Try calling to_f , you should get a float.

For more complex string conversion methods, see here .

+74
Mar 31 '12 at 14:33
source share

You can also use a decimal class for it.

a = '2.45' Decimal(a) 2.45

UPDATE:

Use bigdecimal as @ bigtex777:

source: http://ruby-doc.org/stdlib-2.2.2/libdoc/bigdecimal/rdoc/BigDecimal.html

+2
Jul 22 '15 at 18:15
source share

Header conversion methods are a well-established Ruby idium. Watch this great post from Advi Grimm

 Integer("641339524823408659") => 641339524823408659 
+1
Mar 28 '16 at 0:29
source share

You can also use sprintf for the exact number of decimal points:

 a = 2.45 p sprintf "%.6f", a #=> "2.450000" 
-one
Mar 17 '15 at 21:16
source share



All Articles