2

I am working on a project where it has to take user inputs and do calculations.

What I am aiming for is the print to appear as

Inform the customer they saved 0.71 today

Not

Inform the customer they saved 0.7105000000000001 today

Is there something I can put into the same line of code with the print function to have it be rounded? Or do I have to modify each variable.

I can post my code if requested.

John V
  • 37
  • 1
  • 2

3 Answers3

3

You can use the builtin round() function and float formatting:

>>> print "{0:0.2f}".format(round(x, 2))
0.71

Some Notes:

  • {0.2f} will format a float to 2 decimal places.
  • round(x, 2) will round up to 2 decimal places.

Side Note: round() is really necessary IHMO if you want to "round" the number before "display". It really depends on what you're doing!

James Mills
  • 18,669
  • 3
  • 49
  • 62
2

round() is return the floating point value number rounded to ndigits digits after the decimal point. which takes as first argument the number and the second argument is the precision

no = 0.7105000000000001
print round(no, 2)

second solution:

print "%.2f" % 0.7105000000000001
Haresh Shyara
  • 1,826
  • 10
  • 13
0

use decimal instead of round()

from decimal import *

print(round(8.494,2)) # 8.49
print(round(8.495,2)) # 8.49
print(round(8.496,2)) # 8.5


print(Decimal('8.494').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)) #8.49
print(Decimal('8.495').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)) #8.50
print(Decimal('8.496').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)) #8.50
Johnyz
  • 191
  • 1
  • 3