当简单的算术运算被作为x
传递时,函数formatC()
产生错误的数字格式.
例如:
formatC(29, width = 3, format = "d", flag = "0")
> "029"
这是正确的.但当我这样做:
formatC(100*0.29, width = 3, format = "d", flag = "0")
> "028"
我在这里错过了什么?(R版本4.3.2(2023-10-31 ucrt))
当简单的算术运算被作为x
传递时,函数formatC()
产生错误的数字格式.
例如:
formatC(29, width = 3, format = "d", flag = "0")
> "029"
这是正确的.但当我这样做:
formatC(100*0.29, width = 3, format = "d", flag = "0")
> "028"
我在这里错过了什么?(R版本4.3.2(2023-10-31 ucrt))
您正在使用format = "d"
.docs列出了format
参数的各种选项:
等于
"d"
(对于整数)、"f"
、"e"
、"E"
、"g"
、"G"
、"fg"
(对于实数)或"s"
(对于字符串).对于整数,默认为"d"
,对于实数,默认为"g"
.
无论是29
还是0.29 * 100
都不会被R存储为整数,并且它们不相等.你可以在这里看到这个:
class(29) # numeric
class(29L) # integer
sprintf("%.20f", 29)
# [1] "29.00000000000000000000"
sprintf("%.20f", 100 * 0.29)
# [1] "28.99999999999999644729"
使用整数格式会将第二个值截断为28.对REAL使用适当的格式,例如:
formatC(100 * 0.29, width = 3, format = "g", flag = "0")
# [1] "029"
有关发生这种情况的更多原因,请参阅:Why are these numbers not equal?