格式化可解析的浮点文字
Formatting a parsable float literal
我需要使用 printf 格式输出浮点数,这样生成的字符串就是有效的浮点文字。由于数字是任意的,我使用 %g
格式描述符,后跟 f
.
这在一种特定情况下会引发问题:如果尾数为整数且未附加指数。在这种情况下,打印的数字没有小数点和指数,导致非法常数。
例如
3.3 3.3f ok
3000000000000000. 3e+015f ok
0.000000000000003 3e-015f ok
3 3f nok
您看到处理这种特殊情况的简单方法了吗?
if the mantissa in an integer and no exponent is appended. In this case, the number is printed without the decimal point nor exponent
所以使用 %#g
的替代形式。它将始终打印小数点分隔符,但也会禁用从输出中删除尾随零。
我需要使用 printf 格式输出浮点数,这样生成的字符串就是有效的浮点文字。由于数字是任意的,我使用 %g
格式描述符,后跟 f
.
这在一种特定情况下会引发问题:如果尾数为整数且未附加指数。在这种情况下,打印的数字没有小数点和指数,导致非法常数。
例如
3.3 3.3f ok
3000000000000000. 3e+015f ok
0.000000000000003 3e-015f ok
3 3f nok
您看到处理这种特殊情况的简单方法了吗?
if the mantissa in an integer and no exponent is appended. In this case, the number is printed without the decimal point nor exponent
所以使用 %#g
的替代形式。它将始终打印小数点分隔符,但也会禁用从输出中删除尾随零。