Search code examples
pythontkinterlabelrounding

How to convert a floating-point number to a fixed-width string?


I tried to find this question answered, but I haven't found anything related.

I have a variable that can be in a format like 50000.45 or in a format like 0.01.

I need to write this variable in a label that is 4 digits wide.

What is the best way to fit the label showing only the most significant digits?

To better explain, I would like to have for example: for 50000.45: 50000
for 4786.847: 4786
for 354.5342: 354.5
for 11.43566: 11.43
and for 0.014556: 0.0145

Possibly without having to do:

if ... < variable < ...:
    round(variable,xx) 

for all cases.


Solution

  • In order to convert a number into a set number of digits, you can convert the number into only decimals (aka 0 <= n <= 1), then remove the last characters. You can do it like that:

    from math import log10
    
    number = 123.456789
    n_digits = 4
    
    log = int(log10(number) + 1)
    number /= 10**log # convert the number into only decimals
    
    number = int(number*10**n_digits)/10**n_digits # keep the n first digits
    
    number *= 10**log # multiply the number back
    

    Or a more compact form:

    from math import log10
    
    number = 123.456789
    n_digits= 4
    
    log = int(log10(number) + 1) - n_digits
    number = int(number/10**log)*10**log
    

    [Edit] You should use Python round() function in a simpler way:

    number = round(number, n_digits-int(log10(number))-1)