-2

Problem requires to output decimal proportion of negative integers in an unknown list. The desired answer is 0.500000 (6 decimal places), but my program only outputs 0.5. How do I keep the 5 terminal zeroes?

I've tried using the round(number, ndigits) function and getcontext().prec from the Decimal library. All of these have yielded just 0.5.

def plusMinus(arr):
    from decimal import getcontext, Decimal
    getcontext().prec = 6
    negamt = 0
    posamt = 0
    zeroamt = 0
    for i in arr:
        if i < 0:
            negamt += 1
        elif i > 0:
            posamt += 1
        else:
            zeroamt += 1
    print(Decimal(posamt)/Decimal(n), Decimal(negamt)/Decimal(n), Decimal(zeroamt)/Decimal(n))

The expected results for the unknown array are 0.500000, 0.333333, 0.166667; my program returns 0.5, 0.333333, 0.166667.

gmds
  • 19,325
  • 4
  • 32
  • 58
  • If you search on the phrase "Python format float", you’ll find resources that can explain it much better than we can in an answer here. – Prune Mar 22 '19 at 21:54

1 Answers1

1

You want to change the print format. If you want six digits after the decimal point, you can use this format string:

>>> print('{:1.6f}'.format(0.5)})
0.500000
Querenker
  • 2,242
  • 1
  • 18
  • 29