nodemcu string.format 奇怪的结果
nodemcu string.format odd results
我需要浮点数的特定格式:(符号)xx.dd
当尝试为这种格式设置 string.format 时,我得到了奇怪的结果。
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
当然,我有一个简单的解决方法,但我认为这个构建中有问题。
创建于 2018-04-09 15:12
由 SDK 2.2.1(cfd48f3)
上的 Lua 5.1.4 提供支持
BR,
eHc
这是 NodeMCU 中的错误(或未记录的缺陷)。
Lua 通过将 string.format
格式说明符交给 C 标准库的 sprintf
函数来实现大部分处理。 (有些事情 sprintf
允许 Lua 不允许,但 +
应该可以正常工作。)
NodeMCU 已修改 Lua 以将大部分(或全部)标准库调用替换为对 NodeMCU 定义的替换函数的调用(这通常很疯狂,但在嵌入式系统领域可能没问题)。 NodeMCU 的 sprintf
实现不支持 +
.
这是来自 NodeMCU 源代码的相关代码 (c_stdio.c)。请注意,格式说明符中的未知字符会被静默忽略:
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;
}
同样,0
格式目前还没有为数字实现——正如您所注意到的,它只是在左边填充而不考虑符号。
我需要浮点数的特定格式:(符号)xx.dd 当尝试为这种格式设置 string.format 时,我得到了奇怪的结果。
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
当然,我有一个简单的解决方法,但我认为这个构建中有问题。
创建于 2018-04-09 15:12 由 SDK 2.2.1(cfd48f3)
上的 Lua 5.1.4 提供支持BR, eHc
这是 NodeMCU 中的错误(或未记录的缺陷)。
Lua 通过将 string.format
格式说明符交给 C 标准库的 sprintf
函数来实现大部分处理。 (有些事情 sprintf
允许 Lua 不允许,但 +
应该可以正常工作。)
NodeMCU 已修改 Lua 以将大部分(或全部)标准库调用替换为对 NodeMCU 定义的替换函数的调用(这通常很疯狂,但在嵌入式系统领域可能没问题)。 NodeMCU 的 sprintf
实现不支持 +
.
这是来自 NodeMCU 源代码的相关代码 (c_stdio.c)。请注意,格式说明符中的未知字符会被静默忽略:
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;
}
同样,0
格式目前还没有为数字实现——正如您所注意到的,它只是在左边填充而不考虑符号。