Search code examples
pythonpython-3.xstringconcatenationstring-concatenation

How do I concatenate strings of rounded numbers python?


I'm having trouble figuring out an error in how I'm concatenating a string in python.

The goal is to format numbers into a string which I can print with a consistent length.

I've written the following code:

def numPrint(number,roundplace):
    num = round(number, roundplace)
    if num > 0:
        output = ('+' + str(num))
    elif num < 0:
        output = (str(num))
    else:
        output = (' 0.' + '0' * roundplace)    

    if len(output) < (3 + roundplace):
        output2 = (output + '0')
    else:
        output2 = output

    return output2

print(numPrint(0.001, 3))
print(numPrint(0, 3))
print(numPrint(-0.0019, 3))
print(numPrint(-0.01, 3))
print(numPrint(0.1, 3))

I expect it to print:

+0.001
 0.000
-0.002
-0.010
+0.100

however, I'm getting

+0.001
 0.000
-0.002
-0.010
+0.10

How do I add "0"'s to the last one to get it to work?


Solution

  • You just forgot to multiply the zeros for output2:

    if len(output) < (3 + roundplace):
        output2 = (output + ('0'*(3 + roundplace - len(output))))
    else:
        output2 = output
    

    Or if you don't mind using built-in function:

    output2 = output.ljust(3 + roundplace, '0')