Logo

Programming-Idioms

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

Idiom #367 Find the next significant digit

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

For example, `1.00123` is `1.001`.

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

from re import search
from decimal import Decimal
x = str(Decimal(x))
m = search(r'.+?\.0*[^0]', x)
x = float(m.group() if m else x)
import static java.lang.System.out;
String s = "%f".formatted(x);
int i = s.indexOf('.') + 1, n = s.length();
while (i < n)
    if (s.charAt(i++) != '0')
        break;
s = s.substring(0, i);
  str(x,s);
  p := Pos('.',s) + 1;
  while (s[p] = '0') do inc(p);
  setlength(s,p);

New implementation...
< >
reilas