简体   繁体   English

Python-将量值向上舍入为整数的最佳方法是什么

[英]Python - What is the best way to round a float up in magnitude to an integer

I have a floating point number which I would like to round to an integer, but always round up (where 'up' means larger in magnitude) 我有一个浮点数,我想四舍五入为整数,但总是四舍五入(其中“ up”表示幅度较大)

For example, 4.2 would be rounded to 5, and -4.2 would be rounded to -5.0 例如,将4.2舍入为5,将-4.2舍入为-5.0

Is there a nice way to do this that is built into Python? 有内置在Python中的好方法吗? If not, what would you recommend as the most efficient way of performing this operation? 如果没有,您将推荐什么作为执行此操作的最有效方法?

Originally I was just using math.ceil() , until I realized math.ceil(4.2) gives 5, while math.ceil(-4.2) gives -4, which is not what I want. 最初我只是使用math.ceil() ,直到我意识到math.ceil(4.2)给出5,而math.ceil(-4.2)给出-4,这不是我想要的。

One way that to get around this is to use ceil for positive numbers, and floor for the negative ones, but the code starts to look really gross with inline if statements everywhere (I use this operation in multiple places) 解决此问题的一种方法是使用ceil表示正数,使用floor表示负数,但是代码随处可见,内联if语句看起来真的很粗糙(我在多个地方使用了此操作)

Another possibility might be something like math.copysign( math.ceil( abs( x ) ), x ) which also seems a little excessive 另一种可能性可能是诸如math.copysign( math.ceil( abs( x ) ), x ) ,似乎也有些过分

but the code starts to look really gross with inline if statements everywhere (I use this operation in multiple places) 但是代码随处可见,内联if语句看起来真的很粗糙(我在多个地方使用了此操作)

Then write a function: 然后编写一个函数:

def myround(flt):
   return math.ceil(flt) if flt > 0.0 else math.floor(flt)

If you don't want to scatter "inline if statements everywhere", you could defined your own function: 如果您不想散布“内联if语句无处不在”,则可以定义自己的函数:

def my_rounding(x):
    return math.ceil(x) if x > 0. else math.floor(x)

:D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以给定精度舍入 Python 中由浮点数表示的字典键的最佳方法 - Best way to round a Dictionary key represented by a float in Python with a given precision 将浮点数向上舍入到下一个奇数 - Round a float UP to next odd integer 在 Python 中,在整数除法中向零舍入的好方法是什么? - In Python, what is a good way to round towards zero in integer division? 为什么Python将其四舍五入为整数而不是浮点数? - Why Python round it to integer instead of float number? 将小数/浮点数四舍五入为整数时,在 python 中使用 round、floor 或 ceil 有什么区别? - When rounding a decimal/float to an integer, what's the difference between using round, floor or ceil in python? 在Python中分解此字符串的最佳方法是什么? - What is the best way to break up this string in Python? 在 Python 中将输入从 float 向上舍入或向下舍入为 int - Round up or round down an input from float to int in Python 向下舍入和向上舍入浮点到python中的负小数点 - Round Down and Round Up float to negative decimals point in python Python 将整数四舍五入到下一个百 - Python round up integer to next hundred 舍入一个float并以与Python2和Python3兼容的方式将其转换为整数 - Round a float and convert it to an integer in a Python2 and Python3 compatible manner
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM