【问题标题】:Convert float to string in R without losing precision在R中将浮点数转换为字符串而不会丢失精度
【发布时间】:2018-11-22 17:19:36
【问题描述】:

我需要将具有 2 位小数点精度的浮点数据帧转换为字符串。但是,as.character 会在小数部分去掉零:

> as.character(1.00)
[1] "1"
> as.character(1.10)
[1] "1.1"

我希望这些数字保持原始格式,即:

> paste0(1, ".00")
[1] "1.00"
> paste0(1, ".10")
[1] "1.10".

目前我计划运行 for 循环,检查字符串长度并在我的数据帧中应用 paste0(),但这对我来说似乎真的很愚蠢。有简单的方法吗?

【问题讨论】:

    标签: r string


    【解决方案1】:

    我们可以使用sprintf

    sprintf("%0.2f", 1.10)
    #[1] "1.10"
    sprintf("%0.2f", 1.00)
    #[1] "1.00"
    

    【讨论】:

      【解决方案2】:

      我们也可以使用nsmall参数为2的格式函数。

      format(1, nsmall = 2)
      # [1] "1.00"
      format(1.1, nsmall = 2)
      # [1] "1.10"
      

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多