Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #367 Find the next significant digit

Floor a decimal value, x, to the first significant digit.

For example, `1.00123` is `1.001`.

https://en.wikipedia.org/wiki/Significant_figures

#include <cmath>
double i, n {modf(x, &i)},
       y {log(n) / log(.1)},
       d {pow(10, floor(y) + 1)};
x = trunc(x * d) / d;
let i = Math.trunc(x),
    n = x - i,
    y = Math.log(n) / Math.log(.1),
    d = Math.pow(10, Math.trunc(y) + 1)
x = Math.trunc(x * d) / d
import static java.lang.Math.log;
import static java.lang.Math.pow;
double i = (int) x,
       n = x - i,
       y = log(n) / log(.1),
       d = pow(10, (int) y + 1);
x = (int) (x * d) / d;
  str(x,s);
  p := Pos('.',s) + 1;
  while (s[p] = '0') do inc(p);
  setlength(s,p);
from math import modf, log, floor
n, i = modf(x)
y = log(n) / log(.1)
d = 10 ** floor(y + 1)
x = int(x * d) / d

New implementation...
< >
reilas