简体   繁体   English

Python3如何以一定的精度向上舍入(向下)

[英]Python3 How to round up(down) by a certain precision

I need to round up a floating-point number. 我需要四舍五入一个浮点数。 For example 4.00011 . 例如4.00011。 The inbuilt function round() always rounds up when the number is > .5 and rounds down when <= 5. This is very good. 内置函数round()总是在数字> .5时四舍五入,在<= 5时四舍五入。这非常好。 When I want to round something up (down) I import math and use the function math.ceil() ( math.floor() ). 当我想四舍五入时,我import math并使用函数math.ceil()math.floor() )。 The downside is that ceil() and floor() have no precision "settings". 缺点是ceil()floor()没有精确的“设置”。 So as an R programmer I would basically just write my own function: 因此,作为R程序员,我基本上只会编写自己的函数:

def my_round(x, precision = 0, which = "up"):   
    import math
    x = x * 10 ** precision
    if which == "up":
        x = math.ceil(x)
    elif which == "down":
        x = math.floor(x)
    x = x / (10 ** precision)
    return(x)

my_round(4.00018, 4, "up")

this prints 4.0002 此打印4.0002

my_round(4.00018, 4, "down")

this prints 4.0001 这打印4.0001

I can't find a question to this (why?). 我对此没有疑问(为什么?)。 Is there any other module or function I've missed? 还有其他我想念的模块或功能吗? Would be great to have a huge library with basic (altered) functions. 拥有一个具有基本(更改)功能的大型图书馆会很棒。

edit: I do not talk about integers. 编辑:我不谈论整数。

Check out my answer from this SO post . 这篇SO帖子中查看我的答案。 You should be able to easily modify it to your needs by swapping floor for round . 您应该能够通过将floor换成round来轻松地根据需要修改它。

Please let me know if that helps! 请让我知道是否有帮助!


EDIT I just felt it, so I wanted to propose a code based solution 编辑我只是感觉到了,所以我想提出一个基于代码的解决方案

import math

def round2precision(val, precision: int = 0, which: str = ''):
    assert precision >= 0
    val *= 10 ** precision
    round_callback = round
    if which.lower() == 'up':
        round_callback = math.ceil
    if which.lower() == 'down':
        round_callback = math.floor
    return '{1:.{0}f}'.format(precision, round_callback(val) / 10 ** precision)


quantity = 0.00725562
print(quantity)
print(round2precision(quantity, 6, 'up'))
print(round2precision(quantity, 6, 'down'))

which yields 产生

0.00725562
0.007256
0.007255

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM