I need to represent float values as strings with different number of positions after the decimal point, which should be set by variable , not hardcoded like "%.2f"
.
Now I'm using round
approach:
def float_to_str(value, digits):
return str(round(value, digits))
This function cuts extra digits, so the result has no more that specified number of digits. But it doesn't add trailing zeros.
float_to_str(1.3573, 2) => "1.35" - OK
float_to_str(1.3573, 3) => "1.357" - OK
float_to_str(1.3000, 2) => "1.3" - NOT OK (needed "1.30")
Is there a nicer way to implement this function?
You should use the format
function, which can use syntax similar to "%.2f"
, and format that as well:
def float_to_str(value, digits):
return "{value:.{digits}f}".format(value=value, digits=digits)
The formatting mini language also allows for nested replacement:
def float_to_str(value, digits):
return f"{value:.{digits}f}"
You can use *
to denote a variable width in your format string:
def float_to_str(value, digits):
return "%.*f" % (digits, value)
Try this code.
def float_to_str(value, digits):
formatting = '{:.' + str(digits) + 'f}'
return formatting.format(round(value, digits))
For more information about rounding a number but keeping ending zeros in python, see this
Using f-strings is a possible way to go:
def float_to_str(x, n):
return f"{x:.{n}f}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.