Home > database >  How to round down two significant figures in python?
How to round down two significant figures in python?

Time:09-28

I've seen the solutions around but they mostly round up to two significant figures and not down

I have tried these few methods

import math
v = 0.000129
math.floor(v*100)/100

-output-
0.0    

or

v = 0.000129
from decimal import Decimal
float(f"{Decimal(f'{v:.2g}'):f}")

-output-
0.00013

As you can see, I want to have two significant figures but do not want them rounded up. Decimal works to give the two sig figs but it rounds up while math just simply gives me 0.

i.e. a few to test

1999 -> 1900
29901 - > 29000
0.0199 -> 0.019

Thanks!

CodePudding user response:

Mathematical solution without using any string conversion:

def round_down(n, sig_figs):
    import math
    return n - n % 10 ** math.ceil(math.log(abs(n), 10) - sig_figs)


>>> [round_down(n, 2) for n in [1990, 29901, 0.0199]]
[1900, 29000, 0.019]

Caveats:

  • Doesn't work with input of 0
  • Negative numbers are literally rounded in the negative direction, not towards zero (e.g. -0.0199-0.02)

CodePudding user response:

Here is a function I came up with.

The function takes in the number of significant figures you would want to round down to and the number itself

def custom_sig_figs_round_down(n, sig_figs):
    string_num = str(n)
    string_num_len = len(string_num)
    power_of = string_num_len - sig_figs
    if abs(n) > 1:
        return round(n - (n % 10**power_of), power_of)
    else:
        power_of -= 1
        return round(n - (n % 10**(-1 * power_of)), power_of)
  • Related