Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change decimal character in sprintf()

Tags:

r

printf

I can change the decimal character from output using:

> 1/2
[1] 0.5
> options(OutDec = ',')
> 1/2
[1] 0,5

But, this change does not affect sprintf() function.

> sprintf('%.1f', 1/2)
[1] "0.5"

So, my question is: There is an easy way to change it (the decimal character)? I think that I can't use a 'simple' RE because not every . need be traded by ,.

I don't have any idea of how to do it, so I can't say what I've already done.

like image 334
Rcoster Avatar asked Oct 21 '22 08:10

Rcoster


2 Answers

I think you can do this by setting your locale appropriately, making sure that the LC_NUMERIC component is set to a locale that uses a comma as the decimal separator (http://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html).

Sys.setlocale("LC_NUMERIC","es_ES.utf8")
sprintf("%f",1.5)  
## "1,500000"

This gives a warning that R may behave strangely; you probably want to switch LC_NUMERIC back to C as soon as you're done generating output.

like image 80
Ben Bolker Avatar answered Oct 23 '22 00:10

Ben Bolker


Try this

sprintf("%s",format(1.5,decimal.mark=","))
like image 44
Nicolas Ratto Avatar answered Oct 23 '22 02:10

Nicolas Ratto