I want to remove digits from a float to have a fixed number of digits after the dot, like:
1.923328437452 -> 1.923
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
I want to remove digits from a float to have a fixed number of digits after the dot, like:
1.923328437452 -> 1.923
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.
Something simple enough to fit in a list-comprehension, with no libraries or other external dependencies. For Python >=3.6, it's very simple to write with f-strings.
The idea is to let the string-conversion do the rounding to one more place than you need and then chop off the last digit.
Of course, there is rounding happening here (namely for the fourth digit), but rounding at some point is unvoidable. In case the transition between truncation and rounding is relevant, here's a slightly better example:
Bonus: removing zeros on the right
Simple python script -
I did something like this:
At my Python 2.7 prompt:
>>> int(1.923328437452 * 1000)/1000.0 1.923
If you mean when printing, then the following should work: