I can't multiply decimals, in ruby - ruby

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()

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?

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

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

Related

Code should return highest of two numbers entered by the user

This is the code.
puts "Give me a number"
one = gets.chomp
puts "Give me another number"
two = gets.chomp
if one > two
puts "This is the bigger number #{one}"
else
puts "This is the bigger number #{two}"
end
I don't know where my fault is.
you didn't change them to integer, gets.chomp gives you string.
puts "Give me a number"
one = gets.chomp.to_i
puts "Give me another number"
two = gets.chomp.to_i
First, you are gathering input from an external user of your "application", you then have to decide how you want to manage wrong input and conversion.
In any case, gets will return a String
You are going for numbers, but are they Integer, Float ?
Since String is Comparable, your original code will run but will probably not yield the expected returns.
Let's say you are only interested in Integers.
You will have three conversion functions to consider :
Kernel#Integer (which is included in the top-level binding)
String#to_i.
String#to_i will never return an error.
'abcd'.to_i #=> 0
'1.2'.to_i #=> 1
nil.to_i #=> 0
Kernel#Integer will return an error if the String is not a valid Integer. (which I generally find more appropriate for user inputs).
Integer('0') #=> 0
Integer('abcd') #=> ArgumentError
Integer(nil) #=> TypeError
Finally, you will have to compare your inputs. I personnally would use Array#max since it conveys optimal readability (at the expense of performance still, but you do not seem to be in a performance critical system).
My final code would look like this (without error handling):
inputs = []
2.times do
puts 'Give me a number'
inputs << Integer(gets.chomp) # or use gets.chomp.to_i
end
puts "This is the bigger number : #{inputs.max}"
More refactoring can be done but I don't think it would serve for beginners in Ruby.

I keep getting this error in rubyTest.rb:11:in `+': String can't be coerced into Fixnum (TypeError) from Test.rb:11:in `<main>'

Im trying to do a project for school and i can't figure out how to fix this error. The equations I'm using look correct. I can't find the mistake. Are the equations right?
puts "Hello welcome to the bank of homeless people! How may I help you?"
puts "--type 'deposit' to deposit money to your checkings account"
puts "--type 'withdraw' to withdraw money from your checking account"
puts "--type 'display' to display your currant balance"
descion = gets.chomp.downcase
balance=0
case descion
when 'deposit'
puts "how much do you want to deposit?"
deposit = gets.chomp
balance = balance + deposit
puts "#{deposit} has been added to your checking account"
when 'withdraw'
puts "how much do you want to remove?"
withdraw = gets.chomp
balance = balance - withdraw
puts "#{withdraw} has been removed from your checking account"
when 'display'
puts "you have #{balance} in your account"
end
gets returns a string so your equations are trying to add a fixnum with a string.
Try using to_i on deposit and withdraw
A string is not a digit, therefore Ruby is attempting to find a digit but can't find it within your string.
What you need to do is convert the strings into digits..
For example:
x = "1_000"; #<= "1000" normal string
y = "1_000".to_i; #<= 1000 string converted to integer
You can also go one step further and call .to_f which will turn it into a floating point number, or a decimal.
z = "1_000.to_f; #<= 1000.0 string converted to floating point num
I'd suggest you go and look around on the web for some information on strings and how to use them, along with what you can do with them. Here's a good start: http://ruby-doc.org/core-2.0.0/String.html

rounding off to the nearest number ruby

def percent_more
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
end
Now that code will tell you what percent more biggest_number is than smallest_number. But the problem is it prints out a long list of decimals, which are a pain to sort through. So if I wanted the code to only show say the first 3 numbers what would I do??
What you want to use is total_percent_more.round like so:
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more.round}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
See the docs for more info :
http://www.ruby-doc.org/core-2.1.2/Float.html#method-i-round
in ruby versions earlier than 1.9 you'll need to use sprintf like so:
puts "Your biggest number is #{sprintf('%.2f', total_percent_more)}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
You can change the amount of decimal places by changing the number.
See docs for more details:
http://www.ruby-doc.org/core-1.8.7/Kernel.html#method-i-sprintf
result = 10/6.0
puts result
printf("%.3f\n", result)
--output:--
1.66666666666667
1.667
Here is an example how to round to 2 decimal places
amount = 342
puts amount.round(2)
If you wanted to round to the nearest 3 decimal places then something like:
puts amount.round(3)

Multiplying variables in Ruby?

I'm trying to create a simple pay predictor program.
I am capturing two variables, then want to multiply those variables. I have tried doing
pay = payrate * hourrate
but it seems not to work. I was told to put pay in a definition, then I tried to display the variable but it still didn't work. When I looked at the documentation, it seems that I am using the correct operator. Any guesses?
# Simple Budgeting Program
puts "What is your budget type?\nYou can say 'Monthly' 'Weekly' or 'Fortnightly'"
payperiod = gets.chomp
case payperiod
when "Monthly"
puts "You are paid monthly"
when "Weekly"
puts "You are paid weekly"
when "Fortnightly"
puts "You are paid every two weeks."
else
puts "You did not input a correct answer."
end
puts "What is your hourly rate?\n"
payrate = gets.chomp
puts "How many hours have you worked during your pay period?\n"
hourrate = gets.chomp
def pay
payrate * hourrate
end
puts "#{pay}"
preventclose = gets.chomp
The def has nothing to do with it. payrate and hourrate are strings and * means a very different thing to strings. You need to convert them to numbers first with to_i or to_f.
payrate.to_f * hourrate.to_f
You declared pay rate and hour rate as strings. In Ruby, you cannot multiply strings by other strings. However, in Ruby there are type conversions. Ruby's string class offers a method of converting strings to integers.
string = "4"
string.to_i => 4
In your case, you first need to convert BOTH strings to an integer.
def pay
payrate.to_i * hourrate.to_i
end
Here's some great information about strings.
http://www.ruby-doc.org/core-2.1.2/String.html
Hope this helps
Coercing Strings into Numbers, and Back Again
Kernel#gets generally returns a string, not an integer or floating point number. In order to perform numeric calculations, you need to coerce the string into a number first. There are a number of ways to do this, but the Kernel#Float method is often safer than String#to_i because the Kernel method will raise an exception if a string can't be coerced. For example:
print 'Pay Rate: '
rate = Float(gets.chomp)
print 'Hours Worked: '
print hours = Float(gets.chomp)
Of course, operations on floating point numbers can be inaccurate, so you might want to consider using Kernel#Rational and then converting to floating point for your output. For example, consider:
# Return a float with two decimal places as a string.
def pay rate, hours
sprintf '%.2f', Rational(rate) * Rational(hours)
end
p pay 10, 39.33
"393.30"
#=> "393.30"

How to display output with two digits of precision

Here is my code
class Atm
attr_accessor :amount, :rem, :balance
TAX = 0.50
def transaction
#rem = #balance=2000.00
#amount = gets.chomp.to_f
if #amount%5 != 0 || #balance < #amount
"Incorrect Withdrawal Amount(not multiple of 5) or you don't have enough balance"
else
#rem = #balance-(#amount+TAX)
"Successful Transaction"
end
end
end
a=Atm.new
puts "Enter amount for transaction"
puts a.transaction
puts "Your balance is #{a.rem.to_f}"
and my output is
Enter amount for transaction
100 # user enters this value
Successful Transaction
Your balance is 1899.5
as you can see the output, 'Your balance is 1899.5' only displays one digit of precision. I need help to understand and fix the issue. I want two digits of precision in the output.
And also how can I improve this code?
You can use this:
puts "Your balance is #{'%.02f' % a.rem}"
But remember that this code will round your result if you have more than 2 decimal places. Ex.: 199.789 will become 199.79.
It's a fundamental design flaw to store money as a floating point number because floats are inexact. Money should always be stored as an integer in the smallest unit of currency.
Imagine two accounts with 1.005. Display them both, and suddenly there is an extra penny in the world.
Instead store the amount of money in an integer. For example, $1 would be balance = 100 or 100 pennies. Then format the displayed value:
money = 1000
"%.2f" % (money / 100.0)
# => 10.00
number_with_precision(value, :precision => 2)
Should work in Rails

Resources