Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>SUMMARY:</p> <pre><code>double roundit(double num, double N) { double d = log10(num); double power; if (num &gt; 0) { d = ceil(d); power = -(d-N); } else { d = floor(d); power = -(d-N); } return (int)(num * pow(10.0, power) + 0.5) * pow(10.0, -power); } </code></pre> <hr> <p>So you need to find the decimal place of the first non-zero digit, then save the next N-1 digits, then round the Nth digit based on the rest.</p> <p>We can use log to do the first.</p> <pre><code>log 1239451 = 6.09 log 12.1257 = 1.08 log 0.0681 = -1.16 </code></pre> <p>So for numbers > 0, take the ceil of the log. For numbers &lt; 0, take the floor of the log.</p> <p>Now we have the digit <code>d</code>: 7 in the first case, 2 in the 2nd, -2 in the 3rd.</p> <p>We have to round the <code>(d-N)</code>th digit. Something like:</p> <pre><code>double roundedrest = num * pow(10, -(d-N)); pow(1239451, -4) = 123.9451 pow(12.1257, 1) = 121.257 pow(0.0681, 4) = 681 </code></pre> <p>Then do the standard rounding thing:</p> <pre><code>roundedrest = (int)(roundedrest + 0.5); </code></pre> <p>And undo the pow.</p> <pre><code>roundednum = pow(roundedrest, -(power)) </code></pre> <p>Where power is the power calculated above.</p> <hr> <p>About accuracy: Pyrolistical's answer is indeed closer to the real result. But note that you can't represent 12.1 exactly in any case. If you print the answers as follows:</p> <pre><code>System.out.println(new BigDecimal(n)); </code></pre> <p>The answers are:</p> <pre><code>Pyro's: 12.0999999999999996447286321199499070644378662109375 Mine: 12.10000000000000142108547152020037174224853515625 Printing 12.1 directly: 12.0999999999999996447286321199499070644378662109375 </code></pre> <p>So, use Pyro's answer!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload