Home > Net >  Convert in R from numeric to char without changing value
Convert in R from numeric to char without changing value

Time:07-23

I have a data table extracted from SQL Server, using sqlQuery and it looks like this:

| PK | Value1 | Value2 |

|:---- |:------:| ------:|

| A01 | Descrp | 0.062 |

By default, Value1 is char and Value2 is numeric. I would like to transform Value2 to char and to obtain the same result.

I tried to use: df$Value2 <- as.character(df$Value2), but it transform 0.062 to 0.061999998986721

Any ideas on how to keep 0.062, but as a char column?

CodePudding user response:

0.061999998986721 is the full value. You could use round or signif within as_character depending on how the other numbers are formatted. For the example provided:

> as.character(round(0.061999998986721, 3))
[1] "0.062"

> as.character(signif(0.061999998986721, 2))
[1] "0.062"

CodePudding user response:

Assuming you want a constant number of digits:

format(df$Value2, digits = 3)
  • Related