The Python Oracle

How to properly truncate a float/decimal to a specific place after the decimal in python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC F Haydns String Quartet No 53 in D

--

Chapters
00:00 Question
00:56 Accepted answer (Score 1)
01:34 Answer 2 (Score 3)
01:48 Answer 3 (Score 0)
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/1634...

Accepted answer links:
[Decimal.quantize()]: http://docs.python.org/2.7/library/decim...
[math.floor]: http://docs.python.org/2.7/library/math....

Answer 2 links:
[math.floor()]: http://docs.python.org/2/library/math.ht...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #truncate

#avk47



ANSWER 1

Score 3


You are looking for the math.floor() function instead:

>>> import math
>>> math.floor(8./9. * 10) / 10
0.8



ACCEPTED ANSWER

Score 1


So my options to truncating to the tenths place?

The Decimal.quantize() method rounds a number to a fixed exponent and it provides control over the rounding mode:

>>> from decimal import Decimal, ROUND_FLOOR
>>> Decimal('0.9876').quantize(Decimal('0.1'), rounding=ROUND_FLOOR)
Decimal('0.9')

Don't use math.floor on Decimal values because it first coerces them to a binary float introducing representation error and lost precision:

>>> x = Decimal('1.999999999999999999998')
>>> x.quantize(Decimal('0.1'), rounding=ROUND_FLOOR)
Decimal('1.9')
>>> math.floor(x * 10) / 10
2.0



ANSWER 3

Score 0


Multiply by 10, then floor the value.

In some language:

float f = 1/3;
print(f) //Prints 0,3333333333

float q = Math.floor(f*10)/10
print(q) //Prints 0,3