简体   繁体   English

向下舍入和向上舍入浮点到python中的负小数点

[英]Round Down and Round Up float to negative decimals point in python

I'm looking for something to round up and round down at 1,2, and -1 decimal points in python, I have written some logic through it I am able to get the right values for +ve points but still looking round down -ve values.我正在寻找在python中以1,2和-1小数点四舍五入的东西,我已经通过它编写了一些逻辑我能够获得+ ve点的正确值但仍然向下看 - ve 值。

my code is as -:我的代码是-:

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)

Table value is like -表值就像 - 在此处输入图像描述

I am expecting values like我期待像

在此处输入图像描述

This is the complete solution that meets my matrix.这是符合我的矩阵的完整解决方案。

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))

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

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