Ruby - Number Numbers

Introduction

To calculate the selling price or grand total of some item based on its pretax value or subtotal.

Demo

subtotal = 100.00 
taxrate = 0.175  # from  w w w .j a v a  2s .  c  o  m
tax = subtotal * taxrate 
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"

Result

Here is a simple calculator that prompts the user to enter a subtotal:

Demo

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

Result

Here s.to_f is a method of the String class.

It converts 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.

Related Topics

Example