Been tearing my hair out all day over this little problem I have that is proving hard to fix and I'm fairly sure there are things going on under the surface that I am not aware of. Any feedback or help is hugely welcomed.
I have a function which takes in a float value and returns a string of ASCII characters for output onto an LCD screen. The function is thus:
char returnString(float x, bool isTriggTemp)
{
char numberString[3];
char bufferString[2];
char bufferStringDec[7];
int integerVal = (int)x;
if(isTriggTemp == false)
{
int decimalVal = (x-integerVal)*10000;
sprintf(numberString, "%s.%s", itoa(bufferString,integerVal,10),
itoa(bufferStringDec,decimalVal,10));
}
else
{
int decimalVal = (x-integerVal)*1000;
sprintf(numberString, "%s.%s", itoa(bufferString,integerVal,10),
itoa(bufferStringDec,decimalVal,10));
}
return numberString;
}
The reason for the If statement and the bool is that there are two floats that can be passed to the function. One with 1 decimal place, and one with up to 5. I'm not to fussed about the 5 decimal place number as I am comparing the two floats later in the program and the relevant decimals seem roughly consistent.
My query stems from this line:
int decimalVal = (x-integerVal)*10;
When used like this, which is what I would expect to have to use given the above logic, the outputted string reads "X.0" regardless of the X value.
Increasing it to 100:
int decimalVal = (x-integerVal)*100;
Gives me the correct value for only even numbers. (X.2 is fine when the float is X.2), but with odd numbers I seem to get a rounded down version (X.3 float prints X.2, X.5 -> X.4) etc.
When I increase it to 1000, I begin to see the start of the problem:
int decimalVal = (x-integerVal)*1000;
For even values, X.4 for example, I get X.40 printed. And with odd numbers I get 0.01 less than the original float. E.g. X.5 - > X.49.
Obviously there's something amiss here and non-exact decimals are being cut off. A) how can I fix this? and B) Given the arithmetic I would have guessed that *10 should be used but *100 is the order of 10 that gives me the closest to the correct output.
Any help is much appreciated.