How to remove leading "0." in a numeric R variable How to remove leading "0." in a numeric R variable r r

How to remove leading "0." in a numeric R variable


Only when you output a numeric value do you have to choose a concrete representation (i.e., how the number should be formatted). You cannot change a numeric variable from "-0.34" to "-.34"; both are representations for the same number.

However, when you output an expression e, you can choose how it should be formatted. I don't know of any build-in way to leave off the leading "0", but you could always just remove it manually:

> sub("^(-?)0.", "\\1.", sprintf("%.2f", -0.34))[1] "-.34"

You can define a function for convenience, e.g.,

numformat <- function(val) { sub("^(-?)0.", "\\1.", sprintf("%.2f", val)) }


In addition to the existing answers, I wanted to mention that the package weights has a function rd() which can be used to "round numbers to text with no leading zero". Of course, the result is not numeric but character.

library("weights")rd(-0.341, digits=2)[1] "-.34"


I needed to show numbers to 3 decimal places.If you want to print to an arbitrary number of decimal places and you don't want to have to add another package (i.e., the weights package above), then this function (adapted from @stefan's answer) seems to work:

numformat <- function(x, digits = 2) {     ncode <- paste0("%.", digits, "f")    sub("^(-?)0.", "\\1.", sprintf(ncode, x))}

So for example:

> numformat(-.232, 2)[1] "-.23"> numformat(-.232, 3)[1] "-.232"> numformat(-.232, 4)[1] "-.2320"