The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 How To Properly Truncate A Float/Decimal To A Specific Place After The Decimal In Python?
00:35 Answer 1 Score 3
00:45 Answer 2 Score 0
00:58 Accepted Answer Score 1
01:26 Thank you

--

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

--

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