首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中舍入浮点到负小数点

在python中舍入浮点到负小数点
EN

Stack Overflow用户
提问于 2022-05-20 08:58:37
回答 1查看 53关注 0票数 -2

我正在寻找在python中的1,2,-1小数点的集合和舍入的东西,我已经通过它编写了一些逻辑--我能够得到+ve点的正确值,但仍然可以向下查看-ve值。

我的代码为-:

代码语言:javascript
复制
import decimal

outcome = '2156.24611496733'
rounding="Alwayes Down" 
decimal_place = -1

#   for positive values
if rounding == "Alwayes Up":
    decimal.getcontext().rounding = decimal.ROUND_UP

elif rounding == "Alwayes Down":
    decimal.getcontext().rounding = decimal.ROUND_DOWN

#   for negative values
if rounding == "Alwayes Down":
    print(round(float(outcome), decimal_place))

rounding_string = "1." + "0"*int(decimal_place)
decimal_outcome = decimal.Decimal(str(outcome)).quantize(decimal.Decimal(rounding_string))

print(decimal_outcome)

表值就像-

我期待这样的价值观

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-20 10:18:13

这是符合我矩阵的完整解决方案。

代码语言:javascript
复制
import decimal

outcome = '622222.545454545'
rounding="Alwayes Up" 
decimal_place = -1

#   for positive values
if rounding == "Alwayes Up":
    decimal.getcontext().rounding = decimal.ROUND_UP

elif rounding == "Alwayes Down":
    decimal.getcontext().rounding = decimal.ROUND_DOWN
    
rounding_string = "1." + "0"*int(decimal_place)
decimal_outcome = decimal.Decimal(str(outcome)).quantize(decimal.Decimal(rounding_string))

print(decimal_outcome)

# for negative values
if rounding == "Alwayes Up":
    print(round(float(outcome), decimal_place))

elif rounding == "Alwayes Up":
    decimal.getcontext().rounding = decimal.ROUND_UP
    rounding_string = "1." + "0"*int(decimal_place)
    decimal_outcome = decimal.Decimal(str(outcome)).quantize(decimal.Decimal(rounding_string))
    print(float(decimal_outcome))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72316183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档