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?
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?
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.
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)))