Convert float to string in R without losing precision

前端 未结 2 1734
囚心锁ツ
囚心锁ツ 2021-01-20 23:31

I need to convert a dataframe of floats with 2-decimal point precision to strings. However, as.character drops zeros in the decimal part:

> as.character(1.00)         


        
相关标签:
2条回答
  • 2021-01-21 00:27

    We can use sprintf

    sprintf("%0.2f", 1.10)
    #[1] "1.10"
    sprintf("%0.2f", 1.00)
    #[1] "1.00"
    
    0 讨论(0)
  • 2021-01-21 00:35

    We can also use the format function with the nsmall argument to be 2.

    format(1, nsmall = 2)
    # [1] "1.00"
    format(1.1, nsmall = 2)
    # [1] "1.10"
    
    0 讨论(0)
提交回复
热议问题