Paladini
Paladini

Reputation: 4572

Pythonic way to "round()" like Javascript "Math.round()"?

I want the most Pythonic way to round numbers just like Javascript does (through Math.round()). They're actually slightly different, but this difference can make huge difference for my application.

Using round() method from Python 3:

// Returns the value 20
x = round(20.49)

// Returns the value 20
x = round(20.5)

// Returns the value -20
x = round(-20.5)

// Returns the value -21
x = round(-20.51)

Using Math.round() method from Javascript*:

// Returns the value 20
x = Math.round(20.49);

// Returns the value 21
x = Math.round(20.5);

// Returns the value -20
x = Math.round(-20.5);

// Returns the value -21
x = Math.round(-20.51);

Thank you!

References:

Upvotes: 9

Views: 3059

Answers (3)

Jesse Pardue
Jesse Pardue

Reputation: 190

import math
def roundthemnumbers(value):
    x = math.floor(value)
    if (value - x) < .50:
        return x
    else:
        return math.ceil(value)

Haven't had my coffee yet, but that function should do what you need. Maybe with some minor revisions.

Upvotes: 12

Lakshaya Maheshwari
Lakshaya Maheshwari

Reputation: 512

Instead of using round() function in python you can use the floor function and ceil function in python to accomplish your task.

floor(x+0.5)

or

ceil(x-0.5)

Upvotes: 2

Tom Karzes
Tom Karzes

Reputation: 24052

The behavior of Python's round function changed between Python 2 and Python 3. But it looks like you want the following, which will work in either version:

math.floor(x + 0.5)

This should produce the behavior you want.

Upvotes: 7

Related Questions