String Formatting Operations for decimals.

Discussion in 'Python' started by Lacrima, Apr 1, 2010.

  1. Lacrima

    Lacrima Guest

    Hello!

    I need to format a decimal (floating point) number in the following
    way:
    10 results in '10'
    10.5 results in '10.5'
    10.50 results in '10.5'
    10.5678 results in 10.57

    How can I achieve this using standard Python string formatting
    operations?
    Something like '%.2f' works almost as expected:'10.00'
    But I always need trailing zeros to be excluded, i.e. 10.5 should
    result in '10.5' (not '10.50'), and 10 should result in '10' (not
    '10.00').
    So how can I do this?
    Sorry for my English.
    Thanks in advance.

    with regards,
    Maxim
     
    Lacrima, Apr 1, 2010
    #1
    1. Advertisements

  2. Lacrima

    Chris Rebert Guest

    ('%.2f' % 10).rstrip('0').rstrip('.')

    Cheers,
    Chris
     
    Chris Rebert, Apr 1, 2010
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.