0

I was reading this SO post.

e.g. num <- 42

I want to print num as 42.0. Not as "42.0" (character).

I could use:

format(num, nsmall = 1)

But this still formats as a character string and if I try nesting in as.numeric I lose my decimal point.

How can I ensure num is a number with a single decimal point value?

Community
  • 1
  • 1
Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 1
    You'd have to redefine the print method, which would be silly (and difficult). It's one of those things you shouldn't worry about until you get to presenting your results, at which point you just use `format` or `sprintf` to change everything to strings. – alistaire May 18 '17 at 04:14
  • Thanks for the feedback. Actually, it's for hackerrank challenge "ten days of stats", where the second module demands it in this format.. a numeric result for an integer yet to one decimal place. Hackerrank lets you choose any language, including r. But I suspect that this solution is just not possible with r, I noticed someone on the discussion board using r having the exact same issue. Oh well... – Doug Fir May 18 '17 at 05:53
  • I checked it out and it's fine with strings. The `sprintf` approach below works. – alistaire May 18 '17 at 06:54
  • Oh.. really? I tried with Sprintf(), see screen. http://imgur.com/a/Z5uV7 – Doug Fir May 18 '17 at 07:00
  • 2
    You've got to wrap it in `cat` so it doesn't print with the counter in front, which the checker objects to. – alistaire May 18 '17 at 07:02
  • 1
    Hey it worked! Thank you very much – Doug Fir May 18 '17 at 07:03

1 Answers1

1

If you're looking to round a number to one decimal you will use: round(x, digits = 1) This will work for any later logic you use this number in.

If you're looking to print a number, then it will always be a string. My preferred method is sprintf("%.1f",x).

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
  • Thanks, using round() still displays a integer with no decimal places e.g. 42 and not 42.0. The second suggestion using sprintf() results in a string. I don't think what I'm asking for is possible. See my comment above about why I'm asking for this. Thanks all the same... – Doug Fir May 18 '17 at 05:55