68

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
# :(

4 Answers 4

103

You call to_i, you get integer.

Try calling to_f, you should get a float.

For more string conversion methods, look here.

Sign up to request clarification or add additional context in comments.

1 Comment

There is to_d also, as stated in answer by Tau-fan stackoverflow.com/a/51494232/3090068
18

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

Comments

9

You also can use the decimal class for it

a = '2.45'
Decimal(a) # => 2.45

UPDATE:

Use bigdecimal as @bigtex777 mentioned:

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

4 Comments

NoMethodError (undefined method `Decimal' for ... Another "feature / improvement" from the serial "formerly working-code" destruction-team, no doubt.
This doesn't appear to work for either. You can require 'bigdecimal'; BigDecimal.new('3.333')
Yes, looks like Decimal() is a method from some specific ruby version that I couldn't remember. BigDecimal belongs to ruby stdlib. -> ruby-doc.org/stdlib-2.2.2/libdoc/bigdecimal/rdoc/… It's better use it.
BigDecimal.new('3.333') does not work, should be BigDecimal('3.333')
1

Capitalized conversion methods are a well-established Ruby idiom. See this great post from Advi Grimm

Integer("641339524823408659")
=> 641339524823408659

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.