简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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