Question

I'm trying to split real numbers in a C program using the decimal point as the delimter such that such that say, 1234.56 yields

(int) whole_num = 1234 (int) fraction = 56

Any ideas how I can go about doing this? Its been a loooong while since I mucked around with C, see? :)

Was it helpful?

Solution

void split( double num, int& whole_number, double& fraction) {
    fraction = modf(num, &whole_number);
}

This works since modf takes the integer part of the double and returns the fractional part.

OTHER TIPS

Assuming you want to split a string.

strtok_r and your favorite string-to-num function like strtol

If you're dealing with an actual floating-point number, as opposed to a string representation of such, you should use modf for splitting out the integral and fractional parts.

Perl's split splits by regex, so to replicate full functionality you'd need a regex library. For general string-splitting, you may be able to use strtok, but because it changes the string in-place, strtok_r (described on the same page) is recommended instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top