Removing Trailing Zeros in Python [duplicate]

Updated Generalized to maintain precision and handle unseen values: import decimal import random def format_number(num): try: dec = decimal.Decimal(num) except: return ‘bad’ tup = dec.as_tuple() delta = len(tup.digits) + tup.exponent digits=””.join(str(d) for d in tup.digits) if delta <= 0: zeros = abs(tup.exponent) – len(tup.digits) val=”0.” + (‘0’*zeros) + digits else: val = digits[:delta] + (‘0’*tup.exponent) … Read more

PHP prepend leading zero before single digit number, on-the-fly [duplicate]

You can use sprintf: http://php.net/manual/en/function.sprintf.php <?php $num = 4; $num_padded = sprintf(“%02d”, $num); echo $num_padded; // returns 04 ?> It will only add the zero if it’s less than the required number of characters. Edit: As pointed out by @FelipeAls: When working with numbers, you should use %d (rather than %s), especially when there is … Read more