Round to the nearest tenth position

352 Views Asked by At

I'm new to this forum, but I wanted to post this question hoping to know if anyone has come across it.

Is there a formula in math to round down to the closest power of ten?

For example, $n$ : the number, $r$: the round value. if $n = 101\Rightarrow r = 100$. if $n = 322\Rightarrow r = 100$. if $n = 1200\Rightarrow r = 1000$. if $n = 77\Rightarrow r = 10$.

We need this in finance business, where trades are bought in lot sizes of $10, 100, 1000$ etc.

3

There are 3 best solutions below

5
On BEST ANSWER

It sounds like you have to implement the answer as a script in order to use it. Here is how it can be done in python3:

from math import floor, log

def tenpow(x):
    return 10**(floor(log(x,10)))

tenpow(456)

This returns the powers of ten as desired. However, there is a problem - log(1000,10) in python returns 2.999999 not 3, which 'floors' to 2. But, if you write it 10**(floor(round(log(x,10)))) you get the wrong power of ten if the log result rounds up for other values. What is the remedy for this?

EDIT:

def tenpow(x):
    if x > 0:
        return 10**(len(str(x))-1)
    else:
        return 0

tenpow(345)

A better technique, as suggested by Barry Cipra.

0
On

If you always round to the largest previous power of 10, use $$r=10^{\lfloor\log_{10}(n)\rfloor},$$ where $\lfloor x\rfloor$ is the floor function.

3
On

I assume you want the order of magnitude of a given integer, $x$.

Fortunately, $m:=\lfloor \log_{10}(x)\rfloor$ gives exactly that. ($\lfloor • \rfloor$ is the floor function)

You can then consider $10^m$ for the nearest (lower) power of 10.