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.
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!
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
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
Related
Can anyone tell how to get precision of 2 digits after decimal number in python arithmetic.I want float number to be printed with 2 digits after decimal.
I have used round() function but still not getting correct output.
Thanks in advance
num = 3.1415
print '%.2f' % num # prints 3.14
The f is a floating point number place holder. .2 indicates 2 decimal places when formatting num.
Edit: What is wrong with round?
print round(3.1415, 2) # 2 is decimal places
I was investigating different rounding method using Python built-in solution and some other external libraries such SymPy and while doing so I stumbled upon some cases that I need help with understanding the reason behind it.
Ex-1:
print(round(1.0065,3))
output:
1.006
In the first case, using the Python built-in rounding function the output was 1.006 instead of 1.007 and I can understand that this is not a mistake as Python rounds to the nearest even and that's known as Bankers rounding.
And this is why I from the beginning started searching for another way to control the rounding behaviour. With a quick search, I've found decimal.Decimal module which can easily handle decimal values and efficiently round is using quantize() as in this example:
from decimal import Decimal, getcontext, ROUND_HALF_UP
context= getcontext()
context.rounding='ROUND_HALF_UP'
print(Decimal('1.0065').quantize(Decimal('.001')))
output:1.007
This is a very good solution but the only problem is it is not easy to be hardcoded in long math expressions as I'll need to convert every number to string then after using decimal I will pass it the precession as in the form of "0.001" instead of writing '3' directly as in the case of built-in round.
While searching for another solution I found that SymPy, which I already use a lot in my scripts, offers some very powerful functions that might help but when I tried it the output was not as I expected.
Ex-1 using SymPy sympify():
print(sympify(1.0065).evalf(3))
output: 1.01
Ex-2 using SymPy N (normalize):
print(N(1.0065,3))
output: 1.01
Af first the output was a little bit weird but after investigating I realized that N and sympify already performing round right but rounding to significant figures, not to decimal places.
And here the questions come:
As I can use with Decimal objects getcontext().rounding='ROUND_HALF_UP' to change the rounding behaviour, is there a way to change the N and sympify rounding behaviour to decimal places instead of significant figures?
Instead of re-implementing decimal rounding in SymPy, perhaps use decimal to do the rounding, but hide the calculation in a utility function:
import sympy as sym
import decimal
from decimal import Decimal as D
def dround(d, ndigits, rounding=decimal.ROUND_HALF_UP):
result = D(str(d)).quantize(D('0.1')**ndigits, rounding=rounding)
# result = sym.sympify(result) # if you want a SymPy Float
return result
for x in [0.0065, 1.0065, 10.0065, 100.0065]:
print(dround(x, 3))
prints
0.007
1.007
10.007
100.007
The n of evalf gives the first n significant digits of x (measured from the left). If you use x.round(3) it will round x to the nth digit from the decimal point and can be positive (right of decimal pt) or negative (left of decimal pt).
>>> for x in '0.0065, 1.0065, 10.0065, 100.0065'.split(', '):
... print S(x).round(3)
0.006
1.006
10.007
100.007
>>> int(S(12345).round(-2))
12300
First of all, N and evalf are essentially the same thing; N(x, n) amounts to sympify(x).evalf(n). In your case, since x is a Python float, it's easier to use N because it sympifies the input.
To get three digits after decimal dot, use N(x, 3 + log(x, 10) + 1). The adjustment log(x, 10) + 1 is 0 when x is between 0.1 and 1; in this case the number of significant digits is the same as the number of digits after the decimal dot. If x is larger, we get more significant digits.
Example:
for x in [0.0065, 1.0065, 10.0065, 100.0065]:
print(N(x, 3 + log(x, 10) + 1))
prints
0.006
1.007
10.007
100.007
The transition from 6 to 7 is curious, but not entirely surprising. These numbers are not exactly represented in binary system, so the truncation to nearest double-precision float may be a factor here. I've made a few additional observation on this effect on my blog.
I am getting output 15.36 but I want only 15. I am using round function e.g round(15.36,2) but still getting the same result.
The documentation explains the arguments for the round function pretty well:
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
So if you want to round to the nearest integer just use it without the second argument:
>>> round(15.36)
15
Use the round function in python
round(number, ndigits)
So, for your example use round(15.36,0)
I am trying to write a function to round a floating point number up to n decimal places. The function can take one or two arguments. If there is only one argument the number should be rounded to two decimal places.
This is where I have gotten so far:
def roundno(num,point=2):
import math
x=1*(math.pow(10,-point))
round=0
while (num>x):
while(num>0):
round+=num/10
num=num/10
round*=10
round+=num/10
num=num/10
round*=0.1
return round
I am getting infinity as the output, every time... Where did I go wrong?
I can't see how your algorithm is supposed to round numbers. I guess a similar strategy could work, but you'd need a subtraction in there somewhere...
One way to do this would be to convert the argument to a string, adjust the number of digits after the decimal point, and then convert the string back to a float, but I suspect that your teacher would not like that solution. :)
Here's a simple way to do rounding arithmetically:
def roundno(num, point=2):
scale = 10.0 ** point
return int(num * scale) / scale
data = [123, 12.34, 1.234, 9.8765, 98.76543]
for n in data:
print n, roundno(n), roundno(n, 3)
output
123 123.0 123.0
12.34 12.34 12.34
1.234 1.23 1.234
9.8765 9.87 9.876
98.76543 98.76 98.765
This simply drops unwanted digits, but it's not hard to modify it to round up or off (your question isn't clear on exactly what type of rounding you want).
Note that this function doesn't check the point argument. It really should check that it's a non-negative integer and raise ValueError with an appropriate error message otherwise.
I am working on a program that stores numbers as floats which I eventually write to a file as currency. I am currently using the round() function to round it to 2 decimals, but the business area would like me to round to the next penny no matter what the third decimal is. For example:
x = 39.142
In this case I am trying to get x to round up to 39.15. Obviously when I do the round function I get 39.14...
>>> round(x, 2)
39.14
Is there a way I can always round up to the next penny? I should mention that the numbers I am dealing with are printed to the file as currency.
Using the decimal module:
import decimal
D = decimal.Decimal
cent = D('0.01')
x = D('39.142')
print(x.quantize(cent,rounding=decimal.ROUND_UP))
# 39.15
Decimals have many options for rounding. The options and their meanings can be found here.
if you want to write it in cents, you could use int(x*100+.5) to get cents integer from float dollars.
Very late to this, but in case anyone wants a simple one-liner in Python 3:
import math
x_rounded = math.ceil(x*100) / 100