0

Is there an function in python 2 that can do this?

1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3

Basically the second number says the precision of the number and the everything behind should be rounded.

Based on the comment i came up with this:

def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision

But this is still wrong, because i don't know the size of the numbers.

user3680510
  • 277
  • 2
  • 9

2 Answers2

1

Here's a solution (written step by step for clarity).

import math

num_digits = lambda x: int((math.log(x, 10)) + 1)

def round(x, precision): 
    digits = num_digits(x) 
    gap = precision - digits
    x = x * (10 ** gap)
    x = int(x) 
    x = x / (10 ** gap)
    return x

results:

round(1234, 2) # 1200
round(1234, 3) # 1230
round(12.34, 3) # 12.3
Roy2012
  • 11,755
  • 2
  • 22
  • 35
0

I found a solution:

def round_to_precision(x, precision):
    fmt_string = '{:.' + str(precision) + 'g}'
    return float(fmt_string.format(x))


print round_to_precision(1234, 2)
print round_to_precision(1234, 3)
print round_to_precision(12.34, 3)
user3680510
  • 277
  • 2
  • 9