lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I should sometimes try things (or read more closely) before I offer advice.

format type %E (as in %8.0E) does indeed kill decimal points, but it also
reduces the number to a single digit of precision. So what you actually
want is to do something like divide the number by, say, 1000000, then use
"%13.6E" as a format (which will give you 1 digit before and six after the
decimal point), and then gsub away the offending characters. (That's
assuming your numbers only need 7 digits of precision, otherwise adjust the
1000000 and the format accordingly.)

I felt so bad about this that I contribute the following. I can't guarantee
that it's safe because it's possible that some locale uses something
unusual for a minus sign. Hope it helps.

function safershow(n)
  local retval = gsub(format("%13.6E", n / 1000000), "[^-0123456789eE]",
"")
  return retval
end

> print(safershow(27.4))
2740000E-05
> print(safershow(27.4324))
2743240E-05
> print(safershow(314159))
3141590E-01
> print(safershow(.314159))
3141590E-07
> print(safershow(-2467.18))
-2467180E-03
> print(safershow(1E93))
1000000E87