0

How does one, computationally and dynamically, derive the 'ths' place equivalent of a whole integer? e.g.:

  • 187 as 0.187
  • 16 as 0.16
  • 900041 as 0.900041

I understand one needs to compute the exact th's place. I know one trick is to turn the integer into a string, count how many places there are (by how many individual characters there are) and then create our future value to multiply against by the tenth's value derived - like how we would on pen and paper - such as:

char integerStr[7] = "186907";
int strLength = strlen(integerStr);
double thsPlace = 0.0F;
for (int counter = 0; counter < strLength; ++counter) {
    thsPlace = 0.1F * thsPlace;
}

But what is a non-string, arithmetic approach to solving this?

rjs
  • 838
  • 2
  • 10
  • 21

4 Answers4

4

pseudocode:

n / pow(10, floor(log10(n))+1)
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • This would likely outperform the accepted answer (substantially). – Sam Harwell Jun 11 '14 at 02:27
  • I actually find this to be better, because of the above comment (just noticed it: I'm at work and switching back and forth) but I fear it's legibility can misplace some, albeit it basically reads "Divide n by 10 to the power of (log10n - or, how many 10's fit into n)" – rjs Jun 11 '14 at 02:32
  • thanks for the upvotes. I had to do something similar recently to round numbers to x number of significant digits – Fabricator Jun 11 '14 at 02:38
  • 1
    Do you want `floor(log10(n)) + 1` instead of `ceil(log10(n))`? It seems to me that e.g., `1` should map to `0.1`. – Mark Dickinson Jun 11 '14 at 06:34
1

Divide the original value by 10 repeatedly until it's less than one:

int x = 69105;
double result = (double) x;
while (x > 1.0) x /= 10.0;
/* result = 0.69105 */

Note that this won't work for negative values; for those, you need to perform the algorithm on the absolute value and then negate the result.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • Doy! Simple enough. Negative values are easy enough to tackle with the right control structures in place to check. Thanks! – rjs Jun 11 '14 at 02:17
1

[edited for strange indenting]

I'm not sure exactly what you mean with your question, but here's what I would do:

int placeValue(int n)
{
    if (n < 10)
    {
        return 1;
    }
    else
    {
        return placeValue(n / 10) + 1;
    }
}

[This is a recursive method]

EchoAce
  • 89
  • 4
0

I don't know how performant the pow(10, x) version is, but you could try to do most of this with integer arithmetic. Assuming we are only dealing with positive values or 0 (use the absolute value, if necessary):

  int divisor = 1;
  while (divisor < x)
    divisor *= 10; 
  if (divisor > 0)
    return (double)x / divisor; 

Note that the above needs some safeguards, i.e. checking if divisor may have overflow (in that case, it would be negative), if x is positive, etc. But I assume you can do that yourself.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94