-2

I'd like to output temperature in a log, with values between 0 and 30. I'd like the decimal separators to be aligned between rows and also the number of decimals to be fixed, e.g.:

a =  7.56, s = 20.00
a = 21.03, s = 20.00    
a = 20.01, s = 20.00
a =  1.10, s =  5.00

The actual numbers may be irrational, and they should be rounded to 2 places after the decimal separator. Ideally I'd like to use the f-strings for code readability, but any other format specification would also be OK. Can I achieve this, without rounding and generating the strings myself? All my attempts (and Googling) so far failed: I cannot keep the number of digits after decimal point fixed.

texnic
  • 3,959
  • 4
  • 42
  • 75

2 Answers2

1

Un esempio:

def print_numbers(numbers):
    for couple in numbers:
        print("a = %6.2f,   b = %6.2f" % (couple[0],couple[1])) 

numbers = [(7.56000,20.0000),(21.030,20.000),(20.0100000,20.000000),(1.1000,5.000)]
print_numbers(numbers)

Output:

a =   7.56,   b =  20.00
a =  21.03,   b =  20.00
a =  20.01,   b =  20.00
a =   1.10,   b =   5.00

Format %:

%s - Stringa (o qualsiasi oggetto che possa essere rappresentato con una stringa, ad esempio numeri)
%d - Interi
%f - Numeri reali/virgola mobile
%.<number of digits>f - Numeri in vigola mobile con un un numero fisso di cifre decimali.
%x/%X - Rappresentazione esadecimale di numeri interi (minuscolo/maiuscolo)

es. %-8.3d    (- -> allineamento a sinistra, 8 -> campo minimo di 8 colonne, 3 -> cifre decimali, d -> tipi interi) 
1

Here is the function formatted that would help in aligning by the decimal value.

Plus: dots appear if the number is larger than the donated space:

def main():
    numbers = [1.2345, 12.345, 123.45, 1234.5]
    for number in numbers:
        print(formatted(number, 4, 3))

def formatted(value, int_places=2, dec_places=2):
    total_places = int_places + dec_places + 1
    formatted_value = f'{value:{total_places}.{dec_places}f}'
    if len(formatted_value) > total_places:
        return '.' * total_places
    else:
        return formatted_value
if __name__ == "__main__":
    main()
Bilal Qandeel
  • 727
  • 3
  • 6