4

I need a specific format for a float number: (sign)xx.dd when trying to set a string.format for thiss format I get odd results.

h= 5.127 --(it should beconverted to +05.13)

print(string.format("%+05.2f",h))
-->  05.13 

print(string.format("%+06.2f",h))
--> 005.13

h= -5.127 --(it should beconverted to -05.13)

print(string.format("%05.2f",h))
--> -5.13

print(string.format("%06.2f",h))
--> 0-5.13

Of course, I have an easy workaround, but I think that there is something wrong in this build.

build created on 2018-04-09 15:12 powered by Lua 5.1.4 on SDK 2.2.1(cfd48f3)

BR, eHc

eHc
  • 41
  • 4

1 Answers1

0

This is a bug (or undocumented deficiency) in NodeMCU.

Lua implements most of the handling of string.format format specifiers by handing them off to the C standard library's sprintf function. (There are a few things sprintf allows that Lua doesn't, but + ought to work fine.)

NodeMCU has modified Lua to replace most (or all) of the standard library calls with calls to replacement functions defined by NodeMCU (which is normally crazy, but maybe okay in the embedded systems domain). NodeMCU's sprintf implementation doesn't support +.

This is the relevant code from NodeMCU's source (c_stdio.c). Notice that unknown characters in the format specifier are silently ignored:

for (; *s; s++) {
    if (strchr("bcdefgilopPrRsuxX%", *s))
        break;
    else if (*s == '-')
        fmt = FMT_LJUST;
    else if (*s == '0')
        fmt = FMT_RJUST0;
    else if (*s == '~')
        fmt = FMT_CENTER;
    else if (*s == '*') {
        // [snip]
        // ...
    } else if (*s >= '1' && *s <= '9') {
        // [snip]
        // ...
    } else if (*s == '.')
        haddot = 1;
}

Similarly, the 0 formatting is not implemented currently for numbers -- as you have noticed, it just pads on the left regardless of sign.

tehtmi
  • 676
  • 4
  • 7
  • Ok, thanks a lot. Look also to print(string.format("%06.2f",h)) for a negative value --> 0-5.13, which is really strange. – eHc Apr 27 '18 at 06:00
  • Yes, that is also a bug in NodeMCU's sprintf implementation -- the zero padding doesn't respect the sign for number formats. – tehtmi Apr 27 '18 at 07:21
  • @tehtmi feel free to file bugs against NodeMCU at https://github.com/nodemcu/nodemcu-firmware/issues – Marcel Stör Apr 27 '18 at 12:02