Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display output with two digits of precision

Tags:

ruby

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?

like image 800
Akash Soti Avatar asked Aug 02 '12 17:08

Akash Soti


People also ask

How do I print 2 digits after a decimal?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.

How do you show float to 2 decimal places?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


3 Answers

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.

like image 156
MurifoX Avatar answered Nov 13 '22 15:11

MurifoX


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
like image 32
AJcodez Avatar answered Nov 13 '22 15:11

AJcodez


number_with_precision(value, :precision => 2)

Should work in Rails

like image 30
Anthony Alberto Avatar answered Nov 13 '22 14:11

Anthony Alberto