I have floating point numbers with two decimal places, like 23.46. I want to extract two integers, in this case 23 and 5. The 5 is the result of rounding up the 0.46 to 0.5 and converting it to an integer. The following sketch works but is there a neater way to do it? Lot of code for what seems a trivial task?
float full = 23.46;
int integerPart; // Need result of 23
float decimalPart; // But need 5, not 5.0 etc.
void setup()
{
Serial.begin(115200);
delay(200);
Serial.println("Sketch = ExtractTwoIntegersFrom2DPFloat");
integerPart = (int) full;
Serial.print("integerPart = ");
Serial.println(integerPart);
decimalPart = full - integerPart;
// Round two decimals to one by adding 0.05 & truncating
decimalPart = decimalPart + .05;
// But to get int needed, had to introduce another variable
int decimalPartAsInt = 10 * decimalPart;
Serial.print("decimalPartAsInt = ");
Serial.println(decimalPartAsInt);
}
void loop()
{
}
You take the integral part like you already do
You subtract this integral part from the float, what is left behind the decimal you multiply by 10 for example + 0.5 and you take the integral part again (if you want a single rounded decimal digit)
That does the job, thanks to both you and @awneil.
Now I need to understand it!
And surprisingly it has hardly any fewer lines of code in total than my original?
In my Macro Express Pro app there's a 'Split String' command and I was wondering if there was an Arduino/C equivalent? I suppose modf() is close?.
Manipulating mixtures of different types of variable is an aspect I'm finding hard work!
You don’t have a String to begin with but if really really you want to use Strings you could
float f = 43.21;
String f_s = String(f, 1); // as a String with one decimal digit
Then you can find the dot using indexOf() and extract subString for what’s before and after the dot then use toInt() to transform the subStrings back into numbers
See the string class API
(We would of course not recommend this at all, big waste of SRAM and CPU cycles)