5

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.

Rcoster
  • 3,100
  • 2
  • 15
  • 35
  • perhaps?? change your system locale (`Sys.setlocale`) to one that uses a comma as the decimal separator? http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x – Ben Bolker May 10 '14 at 21:57
  • I'm already on one that uses comma as decimal (Sys.getlocale() `"LC_COLLATE=Portuguese_Brazil.1252;LC_CTYPE=Portuguese_Brazil.1252;LC_MONETARY=Portuguese_Brazil.1252;LC_NUMERIC=C;LC_TIME=Portuguese_Brazil.1252"`) . – Rcoster May 10 '14 at 21:59
  • I think your problem is that you have `LC_NUMERIC=C`. `Sys.setlocale("LC_NUMERIC","es_ES.utf8"); sprintf("%f",1.5)` gives `"1,500000"` for me (along with 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). – Ben Bolker May 10 '14 at 22:03

2 Answers2

2

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.

Ben Bolker
  • 192,494
  • 24
  • 350
  • 426
  • I got this error after `Sys.setlocele`: `2: In Sys.setlocale("LC_NUMERIC", "es_ES.utf8") : OS reports request to set locale to "es_ES.utf8" cannot be honored`... I tried change `es` to `pt`, but gives same error message – Rcoster May 11 '14 at 14:36
  • you probably need `Portuguese_Brazil.1252` (I always have a hard time figuring out what locales are available on my computer; on unix `locale -a` does it: maybe http://superuser.com/questions/166089/where-is-the-list-of-available-windows-locales is helpful – Ben Bolker May 11 '14 at 14:43
  • Still not working here... don't know why, worked with my friends :/ But now I have an idea of what I need to do! Thanks! – Rcoster May 12 '14 at 14:32
1

Try this

sprintf("%s",format(1.5,decimal.mark=","))