Round based on number of digits

28 Views Asked by At

I am not a mathematician, but a programmer. My task is to round integers as follows:

12 → 12
115 → 120
1115 → 1100
11115 → 11000

So you see only the first two digits are precise - the others are just filled with zeroes after rounding the first 3 digits. No problem for a programmer - but I would prefer a simple formula instead of a function which strips characters.

1

There are 1 best solutions below

1
On BEST ANSWER

Scale the first three digits and divide by $10$ (= scale the first two digits),

$$\frac{v}{10^{\lfloor\log_{10}v\rfloor-1}},$$

round to integer,

$$\left\lfloor\frac{v}{10^{\lfloor\log_{10}v\rfloor-1}} +0.5\right\rfloor,$$

fill with zeroes,

$$\left\lfloor\frac{v}{10^{\lfloor\log_{10}v\rfloor-1}} +0.5\right\rfloor10^{\lfloor\log_{10}v\rfloor-1}.$$

E.g. $115\to11.5\to12\to120$, $1115\to11.15\to11\to1100$.

More compactly,

$$[vs^{-1}] s$$ where $s$ is the scaling factor $10^{\lfloor \log_{10}v\rfloor-1}$ and the angle brackets denote rounding.