3

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!

2
  • 2
    That's a very odd request. "0.020" and "0.0199" represent the same value. "0.019" is an entirely different value. I can't think of a way to do this without converting to string and converting back again. Commented Sep 27, 2022 at 22:07
  • I think you may need to write your own rounding algorithm for this...not hard, but as stated it is an odd need so I'd bet it is not already written. For example you are asking for a variable number of 'rounded' variables/digit places, so the logic seems custom not predefined for normal usage, but either way custom writing it, you probably need to add a signature arg to whatever method you create to allow for the location you want to round down in decimal places Commented Sep 27, 2022 at 22:17

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

hey thanks for this, it works so far but when I tried round_down(0.00129,2) the output is 0.0012000000000000001. It seems like if theres more than two zeroes after the decimal it will append a number all the way behind. Any idea how to get rid of that?
Not much you can do about floating point quirkiness. Even "normal" calculations can give these kinds of results (e.g. 12 * 0.0001 == 0.0012000000000000001).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.