I need to truncate / round / justify all the elements of a list to 8 characters. The input list can contain int (that are never too long), str (that I can truncate) and floats as float float64 or str.
Below is a sample of my code :
data = [12452, "too much characters", 0.12457544512, -0.12457544512, "-1245154.8"] processedData = [] for d in data: processedValue = str(d) if len(processedValue) > 8 and '.' in processedValue: decIndex = processedValue.index(".") processedValue = str(round(float(processedValue), 8 - (decIndex + 1))) elif len(processedValue) > 8: processedValue = processedValue[:8] processedData.append(processedValue.rjust(8, " ")) print(processedData) The output and desired output :
[' 12452', 'too much', '0.124575', '-0.12458', '-1245150.0'] # Output [' 12452', 'too much', '0.124575', '-0.12458', '-1245155'] # Desired Output When the decimal is near the end of the 8 characters, my values are not rounded at the correct index. When I replace the elif condition by if, the length is correct but the last digit is still wrong. I've tried some other changes ending up in introducing errors for the other values.