5

Python, version 2.7.3 on 64-bit Ubuntu 12.04

I have a floating point number between 0 and 99.99. I need to print it as a string in this format:

WW_DD

where WW are whole digits and DD are the rounded, 2 digits past the decimal place. The string needs to be padded with 0s front and back so that it always the same format.

Some examples:

0.1    -->  00_10
1.278  -->  01_28
59.0   -->  59_00

I did the following:

def getFormattedHeight(height):

    #Returns the string as:  XX_XX   For example:  01_25
    heightWhole = math.trunc( round(height, 2) )
    heightDec = math.trunc( (round(height - heightWhole, 2))*100 )
    return "{:0>2d}".format(heightWhole) + "_" + "{:0>2d}".format(heightDec)

which works well except for the number 0.29, which formats to 00_28.

Can someone find a solution that works for all numbers between 0 and 99.99?

2 Answers 2

8

Format floating point number with padding zeros:

numbers = [0.0, 0.1, 0.29, 1.278, 59.0, 99.9]
for x in numbers:
    print("{:05.2f}".format(x).replace(".","_"))

Which prints:

00_00
00_10
00_29
01_28
59_00
99_90

The :05 means 'pad with zeros using five places' and .2f means 'force show 2 digits after the decimal point'. For background on formatting numbers see: https://pyformat.info/#number.

Hat-tip: How to format a floating number to fixed width in Python

Sign up to request clarification or add additional context in comments.

1 Comment

Simple. Elegant. Nice solution.
1

Your original solution works if you calculate heightDec this way:

heightDec = int(round((height - heightWhole)*100, 0))

First multiply by 100 and then round and convert to int.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.