A Way to Round Floats Down

How to round float down to a given precision?

Something like this should work for whatever number of digits you want to do:

>>> import math
>>> def round_down(num,digits):
factor = 10.0 ** digits
return math.floor(num * factor) / factor

>>> round_down(2.667,2)
2.66

How do I ONLY round a number/float down in Python?

You can us either int(), math.trunc(), or math.floor(). They all will do what you want for positive numbers:

>>> import math
>>> math.floor(12.6) # returns 12.0 in Python 2
12
>>> int(12.6)
12
>>> math.trunc(12.6)
12

However, note that they behave differently with negative numbers: int and math.trunc will go to 0, whereas math.floor always floors downwards:

>>> import math
>>> math.floor(-12.6) # returns -13.0 in Python 2
-13
>>> int(-12.6)
-12
>>> math.trunc(-12.6)
-12

Note that math.floor and math.ceil used to return floats in Python 2.

Also note that int and math.trunc will both (at first glance) appear to do the same thing, though their exact semantics differ. In short: int is for general/type conversion and math.trunc is specifically for numeric types (and will help make your intent more clear).

Use int if you don't really care about the difference, if you want to convert strings, or if you don't want to import a library. Use trunc if you want to be absolutely unambiguous about what you mean or if you want to ensure your code works correctly for non-builtin types.

More info below:


Math.floor() in Python 2 vs Python 3

Note that math.floor (and math.ceil) were changed slightly from Python 2 to Python 3 -- in Python 2, both functions will return a float instead of an int. This was changed in Python 3 so that both methods return an int (more specifically, they call the __float__ method on whatever object they were given). So then, if you're using Python 2, or would like your code to maintain compatibility between the two versions, it would generally be safe to do int(math.floor(...)).

For more information about why this change was made + about the potential pitfalls of doing int(math.floor(...)) in Python 2, see
Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

int vs math.trunc()

At first glance, the int() and math.trunc() methods will appear to be identical. The primary differences are:

  • int(...)
    • The int function will accept floats, strings, and ints.
    • Running int(param) will call the param.__int__() method in order to perform the conversion (and then will try calling __trunc__ if __int__ is undefined)
    • The __int__ magic method was not always unambiguously defined -- for some period of time, it turned out that the exact semantics and rules of how __int__ should work were largely left up to the implementing class.
    • The int function is meant to be used when you want to convert a general object into an int. It's a type conversion method. For example, you can convert strings to ints by doing int("42") (or do things like change of base: int("AF", 16) -> 175).
  • math.trunc(...)
    • The trunc will only accept numeric types (ints, floats, etc)
    • Running math.trunc(param) function will call the param.__trunc__() method in order to perform the conversion
    • The exact behavior and semantics of the __trunc__ magic method was precisely defined in PEP 3141 (and more specifically in the Changes to operations and __magic__ methods section).
    • The math.trunc function is meant to be used when you want to take an existing real number and specifically truncate and remove its decimals to produce an integral type. This means that unlike int, math.trunc is a purely numeric operation.

All that said, it turns out all of Python's built-in types will behave exactly the same whether you use int or trunc. This means that if all you're doing is using regular ints, floats, fractions, and decimals, you're free to use either int or trunc.

However, if you want to be very precise about what exactly your intent is (ie if you want to make it absolutely clear whether you're flooring or truncating), or if you're working with custom numeric types that have different implementations for __int__ and __trunc__, then it would probably be best to use math.trunc.

You can also find more information and debate about this topic on Python's developer mailing list.

A way to round Floats down

Based on answer from @kimmmo this should be a little more efficient:

class Float
def round_down n=0
s = self.to_s
l = s.index('.') + 1 + n
s.length <= l ? self : s[0,l].to_f
end
end

1.9991.round_down(3)
=> 1.999
1.9991.round_down(2)
=> 1.99
1.9991.round_down(0)
=> 1.0
1.9991.round_down(5)
=> 1.9991

or based on answer from @steenslag, probably yet more efficient as there is no string conversion:

class Float
def round_down n=0
n < 1 ? self.to_i.to_f : (self - 0.5 / 10**n).round(n)
end
end

Rounding down a floating point number to an integer value without a floor function in C

Floor

Use integer cast to round down float number.

float yourFloat = 10.5;
int down = (int)yourfloat; //down = 10.

Nearest integer

To round to the nearest integer, add 0.5f to your float, then cast.

float f1 = 10.3, f2 = 10.8;
int i1, i2;
i1 = (int)(f1 + 0.5f); //i1 = 10
i2 = (int)(f2 + 0.5f); //i2 = 11

Ceil

To round number up, use if statement with some casts:

int result = (int)yourFloat;
if (yourFloat - (int)yourFloat > 0) {
result++;
}

How to perform rounding up or rounding down of a floating point number in python

You can use the round() function which comes builtin in python (https://docs.python.org/2/library/functions.html#round)

>>> round(7.4)
7
>>> round(7.5)
8

From the documentation:

Note the behaviour of round() for floats can be surprising: for
example, round(2.675, 2) gives 2.67 instead of the expected
2.68. This is not a bug: it’s a result of the fact that most decimal
fractions can’t be represented exactly as a float. See Floating Point
Arithmetic: Issues and Limitations for more information.

Round up or round down an input from float to int in Python

Up:

import math
print(math.ceil(4.2))

Down:

import math
print(math.floor(4.2))

How to properly round-up half float numbers?

The Numeric Types section documents this behaviour explicitly:

round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.

Note the rounding half to even. This is also called bankers rounding; instead of always rounding up or down (compounding rounding errors), by rounding to the nearest even number you average out rounding errors.

If you need more control over the rounding behaviour, use the decimal module, which lets you specify exactly what rounding strategy should be used.

For example, to round up from half:

>>> from decimal import localcontext, Decimal, ROUND_HALF_UP
>>> with localcontext() as ctx:
... ctx.rounding = ROUND_HALF_UP
... for i in range(1, 15, 2):
... n = Decimal(i) / 2
... print(n, '=>', n.to_integral_value())
...
0.5 => 1
1.5 => 2
2.5 => 3
3.5 => 4
4.5 => 5
5.5 => 6
6.5 => 7

How can I round down a number in Javascript?

Using Math.floor() is one way of doing this.

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor



Related Topics



Leave a reply



Submit