1

I've found dozen of answers, but non of them is what I'm looking for, I don't want to round up or down, I know that I can round numbers as follow:

>>> print('%.3f' % 15.555555)
15.556

>>> round(15.555555, 3)
15.666

But I need to get 15.555. Should I use regex?

eneepo
  • 1,407
  • 3
  • 21
  • 32

2 Answers2

9

Cheeky solution:

numstring = str(15.555555)
num = float(numstring[:numstring.find('.')+4])
Imre Kerr
  • 2,388
  • 14
  • 34
6

My solution involving int abuse. int rounds towards the nearest 0. I multiply it by 10**3 to affect rounding. After using int, I divide it by 10**3 to get actual results.

It's safer, as it does work with e notation.

int(15.55555 * 10**3) / 10.0**3
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71