def percent_of
puts "What is the number?"
number = gets.chomp.to_f
puts "What is the percent?"
percent = gets.chomp.to_f
total_percent_of = number * percent.to_f
puts " #{percent}% of #{number} is #{total_percent_of.to_i}."
end
Ok so this is a very simple percent of program and works fine. But one thing I don't like is that whenever the console prints out the total it looks like the following example: 75.0% of 417 is 31275.
Now is there any way I could get the total to type out in decimal/money form? Like it should be 312.75 or something like that. Please try and keep your answers simple, I'm new to Ruby. Thank you!
First you need to fix your math. 75% is equal to 75/100 so you want
total_percent_of = number * percent / 100.0
Next you need a format string to ensure that total_percent_of is always printed with the correct number of decimals:
sprintf " #{percent}%% of #{number} is %.2f", total_percent_of
(you need the %% after percent because percent signs have special meaning to sprintf). See the documentation for more information about string formatting.
Related
I'm trying to take the user's input (numbers separated by commas, e.g., "5,8,11"), and return the equivalent number of "-"s. For example, if the user inputs "4,2,4,5", then the output should be the following:
----
--
----
-----
with each on a new line. I need to take an input string, split it at the commas, which will turn it into an array, and then iterate through the array and print the amount of commas per element.
I tried this,
puts "Enter some numbers"
input = gets.chomp
input.split(',')
input.each do |times|
puts "-" * times
end
which returns a noMethodError. I'm not sure where I am wrong.
Any help would be greatly appreciated.
You need integers for that. Try
input = gets.chomp.split(',').map(&:to_i)
Couple of things...
input.split(',')
This DOES split input, but it doesn't change the contents of the input variable.
What would work...
input = input.split(',')
Secondly, the result will be an array of strings, not integers, so better would be...
input = input.split(',').map(&:to_i)
This will map the string array into an integer array
I'm on day one of Ruby and I can't do the most basic of things. The code below is a sample of what I am trying to do. I simply need to add the user input wit the variable. I keep getting a "can't convert float into string" error message.
The more I research a solution, the more it steers me in a different direction. Recasting variables should be pretty simple. I don't understand what i'm doing wrong.
var1 = Float("9.99")
puts "enter in your quantity"
quantity1 = gets + var1
puts "quantity1"
gets returns a string, so you need to cast it to something Numeric in order to add a float to it.
quantity = gets.to_f + var1
will work, but I suggest that you'll do some more reading.
Also you can assign var1 like this: var1 = 9.99
gets stands for get string. You need to convert that string to an integer or a float using the method .to_i (to integer) or .to_f (to float).
I would do this:
var1 = 9.99
puts "enter in your quantity"
quantity1 = gets.to_f + var1
puts quantity1
Note you don't have to specify when a variable is "Float" if you use the decimale separator when you are declaring it. you can see this typing
puts var1.class
it will return Float
When I type the following:
print "2+2 is equal to" +2+2
I get an error message saying I can't convert a number into a string, but when I type:
print "2+2 is equal to", 2+2
it's accepting it and displays:
2+2 is equal to4
What's the difference between the two? It's not making logical sense to me. Could someone please explain it?
print "2+2 is equal to" + 2 + 2
Here you're trying to add a number to a string. This operation doesn't make sense. It's like adding an apple to a cat. The addition fails, but if it were to succeed, then print would print the result.
print "2+2 is equal to", 2 + 2
Here you're telling the print command to print this string and also result of summing these two numbers. it knows how to print strings and how to print numbers. Strings and numbers don't have to be mixed together in this case, they are handled separately. That's why this operation succeeds.
You can make the first operation work too. For this, you must be explicit that you want this number as a string, so that both addition operands are strings and can be actually added together.
print "2+2 is equal to" + (2 + 2).to_s
or
print "2+2 is equal to #{2 + 2}" # this is called string interpolation
Some languages try to be friendly and, if you're adding a number to a string, will stringify the number for you. Results can be... surprising.
Javascript:
"2 + 2 equals to " + 2 + 2
# => "2 + 2 equals to 22"
"2 + 2 equals to " + (2 + 2)
# => "2 + 2 equals to 4"
It's good that ruby doesn't do this kind of tricks :)
Everybody's pointed out how print works, so i thought i'd shed a bit of light on +.
These two operators look the same, right?
'2'+'2'
2+2
In actual fact, there are two very different operations happening:
String#+ - This concatenates the argument to the source string. Argument must be a string.
Fixnum#+ - This adds the argument to the source number. Argument must be a number.
So if String#+ only works on string objects, how is it that we can print different types of objects?
Some classes are very 'string-like' and can be treated as strings in most contexts (eg. Exception before Ruby 1.9) as they implement to_str(implicit conversion).
We can also implement to_s in our own objects to allow it to return a String representation of the object (explicit conversion).
You can read more about this at http://codeloveandboards.com/blog/2014/03/18/explicit-vs-implicit-conversion-methods/
print "2+2 is equal to" +2+2
is equivalent to:
print("2+2 is equal to" +2+2)
You are trying to add an integer 2 to a string "2+2 is equal to".
print "2+2 is equal to", 2+2
is equivalent to:
print("2+2 is equal to", 2+2)
Here print takes two arguemnts, one is a string, the other is an expression 2+2.
print "2+2 is equal to" + 2+2
fails because it tries to add a integer to a string before the result is send to print. An operation that does not make sense. Whereas:
print "2+2 is equal to", 2+2
is a other operation. Here you send two argument to print. A string and an integer. Internally print calls to_s on both values.
From the documentation:
print(obj, ...) → nil
Prints each object in turn to $stdout. [...] Objects that aren't strings will be converted by calling their to_s method.
Another way to do this is string interpolation, that also calls to_s automatically:
print "2+2 is equal to #{2+2}"
I am learning Ruby
I am trying to create a simple script that will convert a given number to roman numerals (old style roman numerals)
I am unable to understand why I get the "can't convert String into Integer (TypeError)"
def convert_to_roman number
romans_array = [[1000,'M'],[500,'D'],[100,'C'],[50,'L'],[10,'X'],[5,'V'][1,'I']]
converted_array = []
romans_array.each do |rom_num|
num = rom_num[0]
letter = rom_num[1]
if number > num
times = number / num
roman_letter = letter*times
converted_array.push(roman_letter)
number = number % num
end
end
converted_array.join()
end
number = ''
puts 'please write a number and I will convert it to old style Roman numerals :)'
puts 'p.s. to exit this program simply hit enter on an empty line, or type 0 and enter :)'
while number != 0
number = gets.chomp.to_i
puts convert_to_roman number
end
My code is at:
https://github.com/stefanonyn/ruby-excercises/blob/master/roman_numerals.rb
You will see that at the end of the file commented out there is an old revision of the code, which actually does work but has a lot of repetition.
I would appreciate if someone could clarify why I get the error described above.
Please don't write the code for me, I am trying to learn Ruby, I would appreciate just some support in moving to the next step.
Thank you very much!
You are missing a comma in your array
romans_array = [[1000,'M'],[500,'D'],[100,'C'],[50,'L'],[10,'X'],[5,'V'][1,'I']]
^ here
This error is definitely not all that helpful, but the reason that it is appearing is that to the interpreter it looks like you are attempting to access a range of indexes in the [5,'V'] array for the last element. However the index's that are being provided go from 1 to 'I' which of course makes no sense. If it had been written [5,'V'][1,1] the last element of the array would be ['V'], which might have been even more confusing to debug!
In a variable is stored this value: $10.00
And I need to get this 10.00
I've tried to convert this value to float:
new_price = '%.2f' % (price.to_f)
but I get just 0.0.
What's wrong with that?
I've tried also
price = price.strip
price[0]=""
new_price = '%.2f' % (price.to_f)
But even this didn't help me... where is a problem?
Thanks
You need to remove the $ first. The whole thing like this:
'%.2f' % '$10.00'.delete( "$" ).to_f
or
'%.2f' % '$10.00'[1..-1].to_f
if you like density and may encounter non dollars.
To set it in a variable:
current_price= '%.2f' % '$10.00'.delete( "$" ).to_f
The more common error, is a value in the thousands where there's a comma in the string like: 10,000.00. The comma will cause the same truncation error, but the decimal won't, and many programmers won't even catch it (we don't even notice the comma anymore). To fix that:
current_price= '%.2f' % '10,000.00'.delete( "," ).to_f
Adding on to froderick's answer of:
You need to remove the $ first. The whole thing like this:
'%.2f' % '$10.00'.delete( "$" ).to_f
or
'%.2f' % '$10.00'[1..-1].to_f
if you like density and may encounter non dollars.
you need to format the code for output to ensure that you get two decimal places >with
You need to format your output string to ensure you get two decimal places.
puts "Current amount: #{format("%.2f", amount)}"