Hey All!
Using round() and String Conversion for Format Decimal Python
One simple way to format decimal Python values is by combining the round()
function and string conversion. The round()
function lets us limit the number of decimal places, and using string conversion allows us to remove any trailing zeroes when unnecessary. Here’s an example:
def format_decimal(value):
return str(round(value, 2)).rstrip('0').rstrip('.') if '.' in str(value) else str(value)
print(format_decimal(1.00)) # Output: '1'
print(format_decimal(1.20)) # Output: '1.2'
print(format_decimal(1.23)) # Output: '1.23'
print(format_decimal(1.234)) # Output: '1.23'
print(format_decimal(1.2345)) # Output: '1.23'
This approach is straightforward for formatting decimal Python numbers and handles values like 1.00, making them return as ‘1’ instead of ‘1.00’.