Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string format a float, how to truncate instead of rounding

Is there a format option such that

>>> '%.1(format)'%2.85

gives '2.8'?

In Python 2.7, 'f' format rounds to nearest

>>> "{:.0f}".format(2.85)
'3'
>>> "%.0f"%2.85
'3'
>>> "%.1f"%2.85
'2.9'
>>> "%i"%2.85
'2'
like image 750
jf328 Avatar asked May 26 '15 14:05

jf328


People also ask

How do you truncate a float to two decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.

Does float truncate?

Float#truncate() is a float class method which return a truncated value rounded to ndigits decimal digits precision.

How do you truncate a string in Python?

Use string slicing to truncate a string Use the syntax string[x:y] to slice a string starting from index x up to but not including the character at index y . If index x is not specified it defaults to zero.


1 Answers

No, there is not. Have a look at the documentation for a complete list of supported floating point format specifiers.

You need to round in your code instead

like image 73
Eric Avatar answered Oct 15 '22 18:10

Eric