Numbers

Numbers are just as easy to use as strings. For example, let’s suppose you want to calculate the selling price or grand total of some item based on its pretax value or subtotal. To do this, you would need to multiply the subtotal by the applicable tax rate and add the result to the value of the subtotal. Assuming the subtotal to be $100 and the tax rate to be 17.5 percent, this Ruby program does the calculation and displays the result:

4calctax.rb

subtotal = 100.00
taxrate = 0.175
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"

Obviously, this program would be more useful if it could perform calculations on a variety of subtotals rather than calculating the same value time after time! Here is a simple calculator that prompts the user to enter a subtotal:

taxrate = 0.175
print "Enter price (ex tax): "
s = gets
subtotal = s.to_f
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"

Here s.to_f is a method of the String class. It attempts to convert the string to a floating-point number. For example, the string "145.45" would be converted to the floating-point number 145.45. If the string cannot be converted, 0.0 is returned. For instance, "Hello world".to_f would return 0.0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.123.73