Convert String to float in R

Asked

Viewed 643 times

1

Hello, how do I convert

b <- format(round(3, 2), nsmall = 2)
[1] "3.00"

Therein

[1] 3.00

I have tried using.Numeric, as.double, but always returns 3 but I need 3.00

  • 1

    Why do you need 3.00 as a numeric? Why does "3.00" as a string not answer?

1 answer

3

I think you’re confusing the number and output of the method print for class objects "numeric", which is the method print.default. The number you have is 3.00.
Otherwise see first how it is represented internally by R.

The function typeofis described as such in the documentation, help("typeof").

Description

typeof determines the (R Internal) type or Storage mode of any Object

Google Translation, edited by me.

Description

typeof determines the type (internal R) or storage mode of any object

typeof(3)
#[1] "double"

That is, the number 3 corresponds to the "double" of the C language, which are floating comma numbers with 64 bits.

To call the method print corresponding to these objects is more useful to know the object class.

class(3)
#[1] "numeric"

As there is no method print.numeric the R executes print.default. You can see the code with the command

print.default

just like that, no parentheses.
This method only prints what is necessary, as only print(3) does not need more decimal places he does not show them.

Try now to see the result of

round(c(3, pi), 2)
#[1] 3.00 3.14

For the result of round(pi, 2) the print needs two decimals so this is used to all vector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.