Splitting a Decimal Value

Difficulty: ★ ★ ☆ ☆

A floating point, or real number, has two parts: Before the decimal comes the integer part. After the decimal is the fractional part. Sometimes it’s necessary to split such a value, so that your code can deal separately with the integer and fractional parts.

Never mind the reason, though it may be coming up in a future Exercise on this blog (hint-hint). Your task for this month’s Exercise is to prompt the user for floating-point input. Hopefully they type a real number, something like 123.456.

In your code, you cleave the value, setting the integer part — 123 in this example — into its own int variable, and putting the fractional part — 456 — into its own float variable. All three values are then output: original, integer, and fractional.

To be kind, I’m providing the following code skeleton to help you get started.

2022_05_01-Lesson.c

#include <stdio.h>

int main()
{
    float input,fractional;
    int integer;

    printf("Enter a decimal value: ");
    scanf("%f",&input);

    /* magic happens here */

    printf("Value %f can be split in to %d and %f\n",
            input,integer,fractional
          );

    return(0);
}

Just replace the comment in the skeleton with your coding brilliance. Ta-da! You’re done.

Here’s a sample run of my solution:

Enter a decimal value: 123.456
Value 123.456001 can be split in to 123 and 0.456001

Remember that floating point values are imprecise, which explains how the fractional portion in the output may not be exact. Still, the point is to separate the values as shown above.

Please try this exercise on your own before you peek at my solution.

4 thoughts on “Splitting a Decimal Value

  1. Sure, though I didn’t require any other functions for my solution.

  2. #include <stdio.h>
    
    int main(void)
    {
    	float input, fractional;
    	int integer;
    
    	printf("Enter a decimal value: ");
    	scanf("%f", &input);
    
    	integer = (int)input;
    	fractional = input - integer;
    
    	printf("Value %f can be split in to %d and %f\n",
    	        input, integer, fractional);
    
    	return (0);
    }

Leave a Reply