# demial points in arrays

I am reading keys pressed on a keypad into an array.  The numbers can vary from 0.01 to 500, with two decimal precision.  I am using the hex code 0X0A to signify a decimal point has been pressed.  I can see how to handle a number lthat begins with a decimal, or has no decimal..but what about soemthing like 206.33, or 0.03?
``````while(keypress()!=0x0B); {  //not the # end signal
newkey[j]=keypress();
j++;
}
}

if (newkey[0]==0x0A)
keytotal=0.1*newkey[1]*0.01+newkey[2];

else
keytotal=newkey[0]+newkey[1]*10+newkey[2]*100;
``````
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Senior Software Engineer (Avast)Commented:
Why don't you just get keypress() to return character representations of numbers and decimal point and then use sscanf() or atof() to do this conversion from string to float? You just need to make sure newKey is null terminated.

http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html

Would this work?

-Rx.
``````#include <stdio.h>
#include <stdlib.h>

int main(void) {
char newKey[] = "206.33"; // Assume this is what's returned by keypress
float keytotal1 = 0;
float keytotal2 = 0;

sscanf(newKey, "%f", &keytotal1); // You could do this...
keytotal2 = (float) atof(newKey); // ...or this

return 0;
}
``````
0
Commented:
Here are two alternatives :
``````/* alternative 1 : calculating as the key presses come in */

unsigned char key = 0x00;
double value = 0.0;
int dec_cnt = -1;
while ((key = keypress()) != 0x0B) {
if ((dec_cnt >= 0) || (key == 0x0A)) ++dec_cnt;
if (key < 0x0A) {
value = (value * 10.0) + ((double) key)
}
}
while (dec_cnt--) {
value /= 10.0;
}

/* alternative 2 : make use of sscanf */

unsigned char key = 0x00;
char value_str[32] = { 0 };
int i = 0;
double value = 0.0;
while ((key = keypress()) != 0x0B) {
if (key == 0x0A) value_str[i++] = '.';
else if (key < 0x0A) value_str[i++] = '0' + key;
}
sscanf(value_str, "%f", &value);
``````
0

Experts Exchange Solution brought to you by