Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Math.round() explanation at Mozilla Developers Network (MDN)
like image 893
Paladini Avatar asked Jan 19 '16 12:01

Paladini


People also ask

How do you round up in math in JavaScript?

ceil() The Math. ceil() function always rounds a number up to the next largest integer.

How do you round a function in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you round a whole number in JavaScript?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

Is there a round up function in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.


3 Answers

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.

like image 121
Jesse Pardue Avatar answered Oct 23 '22 10:10

Jesse Pardue


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.

like image 40
Tom Karzes Avatar answered Oct 23 '22 10:10

Tom Karzes


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)

like image 39
Lakshaya Maheshwari Avatar answered Oct 23 '22 12:10

Lakshaya Maheshwari