-2

I have digits, for example:

100.1264
9.09
123
1298.456789

and I want to truncate this to:

100.12
9.09
123
1298.45

How to truncate those numbers so as to leave their form?

Nips
  • 13,162
  • 23
  • 65
  • 103
  • What do you mean *"digits"*? Are they part of a string, or number objects? Do you want them *displayed* rounded to 2dp, or actually rounded? And what have *you* tried so far? Please provide more information. – jonrsharpe Aug 18 '15 at 09:17
  • nips did you try anything? show us what you tried as a python code. – Ja8zyjits Aug 18 '15 at 09:20
  • please refer this answer this might help you. [here](http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – Navin Dalal Aug 18 '15 at 09:29

2 Answers2

1

If you have numbers (not strings), you can use:

import math
math.trunc(x * 100) / 100

For example:

>>> import math
>>> x = 100.1264
>>> math.trunc(x * 100) / 100
100.12

You may also use int in place of math.trunc, however beware that casts between floats and ints may be computationally expensive.

Bonus tip: if you want arbitrary precision decimal arithmetic, take a look at the decimal module.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
0
s="""100.1264
9.09
123
343.1
1298.456789"""
print re.sub(r"(?<=\.)(\d{2})\d+",r"\1",s)

If your input is a float you can use

s=100.1264

print ast.literal_eval(re.sub(r"(?<=\.)(\d{2})\d+",r"\1",str(s)))
vks
  • 67,027
  • 10
  • 91
  • 124
  • 2
    Casting to a string, regular expression-ing it and converting back (with `literal_eval`, not `float`?!) seems inefficient compared to e.g. `int(s * 100) / 100.0`... – jonrsharpe Aug 18 '15 at 09:29
  • @jonrsharpe round(4.1234) gives `4.0` ? – vks Aug 18 '15 at 09:30
  • Yes, I realised that shortly after commenting. As pointed out elsewhere `math.trunc` is also available though, and the point is that the round trip through string seems like an odd way to approach it. – jonrsharpe Aug 18 '15 at 09:31
  • @jonrsharpe i have no idea `math.trunk` – vks Aug 18 '15 at 09:32