-3

How can I round to two places - not decimal places?

ex.

input: 2.6759, 3.5632, 30.8736, 42.8927
output: 2.7, 3.6, 31, 43
Brandon
  • 89
  • 7
  • 2
    "significant figures" is the keyword you're looking for – Pranav Hosangadi Aug 05 '21 at 19:58
  • 2
    Does this answer your question? [How to round a number to significant figures in Python](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python) Specifically this answer: https://stackoverflow.com/a/48812729/843953 – Pranav Hosangadi Aug 05 '21 at 20:00

1 Answers1

1
import math

def roundx(v):
    scale = int(math.log10(v))
    x = int(v * 10**(1-scale) + 0.5) * 10**(scale-1)
    return x

for v in (2.6759,3.5632,30.8736,42.8927):
    print(roundx(v))

Output:

2.7
3.6
31
43
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30