1

I'm making a interest calculator

I go 10 * .10 * 10 and i get 0 so how do i multiply a decimal without it being 0?

my source code is

 def interest()
    puts "Type the original loan."
    loan = gets.chomp.to_i
    puts "Type the amount of interest in decimal."
    interest = gets.chomp.to_i
    puts "How many years?"
    years = gets.chomp.to_i
    puts "Your interest is"
    puts loan * interest * years
end

interest()
StarsSky
  • 6,721
  • 6
  • 38
  • 63
get52
  • 61
  • 1
  • 9

3 Answers3

6

You've got integers there, so result will be an integer too. You could use 'to_f but beware, it's not good for dealing with money or anything else needing precision. Use BigDecimal instead:

  require 'bigdecimal'
  def interest
    puts "Type the original loan."
    loan = BigDecimal(gets.chomp)
    puts "Type the amount of interest in decimal."
    interest = BigDecimal(gets.chomp)
    puts "How many years?"
    years = BigDecimal(gets.chomp) # suggested in comment, agreed with that
    puts "Your interest is"
    puts loan * interest * years
  end

What's the difference between them?

Community
  • 1
  • 1
zrl3dx
  • 7,699
  • 3
  • 25
  • 35
  • solved thank you, but whats the diff with BigDecimal and to_f? – get52 Jan 06 '14 at 14:17
  • I'd be using BigDecimal for the years also. – David Aldridge Jan 06 '14 at 14:17
  • 1
    @get52: BigDecimal has _infinite_ precision, meaning that YOU can set the precision and it is stored differently than Floating point. Floating point is imprecise, because it is stored in binary format but there are certain numbers that you cannot store in a binary format, therefore they will loose precision. Also, BigDecimal is several magnitude slower to work with, than Floating point. – karatedog Jan 06 '14 at 14:21
  • @get52: added link explaining that. – zrl3dx Jan 06 '14 at 14:21
  • 1
    also have a look here: http://stackoverflow.com/questions/4662138/if-dealing-with-money-in-a-float-is-bad-then-why-does-money-format-do-it – tessi Jan 06 '14 at 14:21
3

Do this

interest = gets.chomp.to_f

.to_i changes the string to an integer. An integer is a WHOLE number.

.to_f is to float, a float is a number that allows decimal places

tessi
  • 13,313
  • 3
  • 38
  • 50
CRABOLO
  • 8,605
  • 39
  • 41
  • 68
1

The problem is that you're using .to_i when you don't really want to use integers here. Integers are represented without decimal parts to them, and therefore when you call .10.to_i it truncates it to 0.

Consider using floats by .to_f instead

marknach
  • 232
  • 2
  • 8