# how could I get each digit in a float into a array of ints?

Printable View

• 05-19-2004
Marcos
how could I get each digit in a float into a array of ints?
Lets say I have
Code:

`        float a = 12.50f;`
and I want to have
Code:

`        int b[4] = { 1, 2, 5, 0 };`
I already have a way to know how many digits the float has if you are interested:
Code:

```        n = 10;         while (1)         {                 Digits++;                 if (n > TheFloat)                         break;                 n *= 10;         }         Digits += 2;```
the last part is for the 2 decimals.
Thanks for any help.
• 05-19-2004
Prelude
By far the best way is to convert the number to a string and then assign each digit to an int array. Here's a quickie example:
Code:

```#include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace std; int main() {   float        a = 12.50f;   int          b[4];   char        ch;   stringstream ss;   ss<< fixed << setprecision(2) << a;   for (int i = 0; ss>> ch; ) {     if (ch == '.') {       continue;     }     b[i++] = ch - '0';   }   for (int i = 0; i < 4; i++) {     cout<< b[i] <<endl;   }   return 0; }```
• 05-19-2004
Marcos
thanks but I am using an old compiler and I dont seem to have the sstream library, if anyone knows of a way to just get like the leftmost digit of the float, then the next digit and so on it would be great. But thanks anyway prelude.
• 05-19-2004
alphaoide
this method uses stdlib.h
http://www.cplusplus.com/ref/cstdlib/ecvt.html

if u want free standard compiler go to www.bloodshed.net
• 05-19-2004
Prelude
>But thanks anyway prelude.
I'm not done yet though. :) You can do it the old fashioned way too:
Code:

```#include <iostream.h> #include <stdlib.h> int main() {   float        a = 12.50f;   int          b[4];   int          i, j;   char        buf[256];   const int    ndigits = 4;   sprintf(buf, "%f", a);   for (i = j = 0; j < ndigits; i++) {     if (buf[i] == '.') {       continue;     }     b[j++] = buf[i] - '0';   }   for (i = 0; i < 4; i++) {     cout<< b[i] <<endl;   }   return 0; }```
• 05-19-2004
Marcos
thanks very very much prelude and alphaoid, I now have what I was looking for and I can sleep in peace :)