title: How to format numbers in R, specifying the number of significant digits but keep significant zeroes and integer part?
body: <p>I've been struggling with formatting numbers in R using what I feel are very sensible rules. What I would want is to specify a number of significant digits (say 3), keep significant zeroes, and also keep all digits before the decimal point, some examples (with 3 significant digits):</p>
  
  <pre><code>1.23456 -&gt; "1.23"
  12.3456 -&gt; "12.3"
  123.456 -&gt; "123"
  1234.56 -&gt; "1235"
  12345.6 -&gt; "12346"
  1.50000 -&gt; "1.50"
  1.49999 -&gt; "1.50"
  </code></pre>
  
  <p><strong>Is there a function in R that does this kind of formatting? If not, how could it be done?</strong></p>
  
  <p>I feel these are quite sensible formatting rules, yet I have not managed to find a function that formats in this way in R. As far as I googled this is not a duplicate of many similar questions such as <a href="https://stackoverflow.com/questions/5225920/how-to-format-a-number-with-specified-level-of-precision">this</a></p>
  
  <p><em>Edit:</em></p>
  
  <p>Inspired by the two good answers I put together a function myself that I believe works for all cases:</p>
  
  <pre><code>sign_digits &lt;- function(x,d){
    s &lt;- format(x,digits=d)
    if(grepl("\\.", s) &amp;&amp; ! grepl("e", s)) {
      n_sign_digits &lt;- nchar(s) - 
        max( grepl("\\.", s), attr(regexpr("(^[-0.]*)", s), "match.length") )
      n_zeros &lt;- max(0, d - n_sign_digits)
      s &lt;- paste(s, paste(rep("0", n_zeros), collapse=""), sep="")
    }
    s
  }
  </code></pre>