Limit Float number to n decimals in Python with example
This tutorial explains multiple ways to limit a decimal in a string or floating number with an example
Python Limit floating number with 2 decimals only
- use template string format from the 3.6 version
{:.2f}
is a template format used to limit the floating number to 2 decimals.
The format
function takes a number, and converts it to a string.
You can convert string to float using the float function
number=1243.997895
number1=1243.12345
number2=1243.1111111997895
print(float("{:.2f}".format(number)))
print(float("{:.2f}".format(number1)))
print(float("{:.2f}".format(number2)))
- Round function in 2.7 version
round function takes a floating number, and number to tell about the limit the decimal places.
round(floatno, limitdecimal)
if number is a string that contains a float number, first convert it into float
str="123.43123123"
print(round(float(str),3))
Here is an example
number=1243.997895
print(round(number,3))
number1=1243.12345
print(round(number1,3))
number2=1243.1111111997895
print(round(number2,3))
Output:
1243.998
1243.123
1243.111
- using the print format function
This is the old way of writing and print float values are limited to display
number=1243.997895
number1=1243.12345
number2=1243.1111111997895
print( "%.2f" % number)
print( "%.2f" % number1)
print( "%.2f" % number2)
1244.00
1243.12
1243.11
- use the format function
format
function takes a floating number and formats the string, converting the string with limit decimals.
you can use the float()
function, to take a string and convert it into a float number
print(float(format(number2, '.2f')));
Here is an example
number=1243.997895
number1=1243.12345
number2=1243.1111111997895
print(format(number, '.2f'))
print(format(number1, '.2f'))
print(format(number2, '.2f'))