开发者

round function not working in python

how do i round off a function.

i have the following code in python

def round(x,n):
    return round(x,n)

i get the following error

>>> round(3,98.9898, 2)

Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
开发者_开发问答round(3,98.9898, 2)
TypeError: round() takes exactly 2 arguments (3 given)

i think the comma is creating the problem

any suggestions.... please thanks

i tried this.

def round(x,n):    
    return round(float(x.replace(",", "")),n)

no luck.


Two issues:

  • round(3,98.9898, 2) is code that you enter. Omit the comma yourself and your problem goes away. Otherwise give us more info about your problem.

  • def round(x, n): return round(x, n)
    Even if you fix your function call, you'll most likely end up with RuntimeError due to maximum recursion. Rename your function to something other than round.


How are you getting that number? If it autogenerated, it must be a string. do a float(number.replace(',','')) when you are using it the number as an argument for round.


Yes, it is the comma. In Python to create floating point numbers you use only the point. Commas do many other things!

EDIT: What do you want to do? What is your number?


Yes, it's the comma. A number cannot have a comma in it. Commas should only be added for display purposes, after all computation, which can be done after converting the number to a string.

If you're dealing with user input, it's going to be a string, and you'll have to strip out commas before converting to a float/int.


I'm gonna step back and start with the basics. Is this your actual code?

round(3,98.9898, 2)

If so, you are passing three parameters into the function: 3, 98.9898, and 2, but the function only accepts two. Perhaps you mean one of the following:

round(98.9898, 2)
round (398.9898, 2)

or some other variation?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜