Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting floating point number in Python with padding of 0s

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?

like image 297
Madeleine P. Vincent Avatar asked Mar 13 '23 11:03

Madeleine P. Vincent


2 Answers

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.

like image 31
Boris Serebrov Avatar answered Apr 07 '23 01:04

Boris Serebrov


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

like image 108
paregorios Avatar answered Apr 07 '23 01:04

paregorios