How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
The TRUNC function simply truncates (i.e. removes) decimal values if they exist – it doesn't do any rounding. The TRUNC function returns the integer portion of the number which is then subtracted from the original value. The result is the decimal portion of the number.
In the C Programming Language, the modf function splits a floating-point value into an integer and a fractional part. The fraction is returned by the modf function and the integer part is stored in the iptr variable.
The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.
You use the modf
function:
double integral; double fractional = modf(some_double, &integral);
You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.
Try this:
int main() { double num = 23.345; int intpart = (int)num; double decpart = num - intpart; printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart); }
For me, it produces:
Num = 23.345000, intpart = 23, decpart = 0.345000
Which appears to be what you're asking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With