CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Oct 2001
    Posts
    745

    Seperating Integer & Fractional Part

    Helo,

    I have a double value ,say 1.4.
    double val = 1.4;
    I want to seperate the Integer & Fractional Part. "1" & "4" from that val like
    int val1 =1
    int val2 = 4(without the ".")

    How Can I do that.
    Thanks...

  2. #2
    Code:
    void main()
    {
    	float a=5.8;
    	int i,j;
    	i=a;
    	j= (a -i) *10;
    
    	printf("%d   %d", i,j);
    }
    but it will work only if your fractional part length is 1.
    Otherwise you won't get the extract fractional portion by this code

  3. #3
    Join Date
    Jun 2002
    Posts
    224
    Try:
    Code:
    double d, ip;
    d = 1.4
    int fp = 10 * modf( d, &ip );
    Regards,
    ZDF

    What is good is twice as good if it's simple.
    "Make it simple" is a complex task.

  4. #4
    Join Date
    Oct 2001
    Posts
    745
    I tried the 2nd choice,bit its not working for 1.2 & 1.4

  5. #5
    Join Date
    Jun 2002
    Posts
    224
    Originally posted by Kohinoor24
    I tried the 2nd choice,bit its not working for 1.2 & 1.4
    It is not clear what “not working” means. I did not check the code, but it should work. If you have rounding problems you may add/subtract 0.5:
    Code:
      int i = int(10. * 0.39); // i == 3
      int j = int(10. * 0.39 + 0.5); // j == 4
    Regards,
    Last edited by zdf; October 30th, 2002 at 05:47 AM.
    ZDF

    What is good is twice as good if it's simple.
    "Make it simple" is a complex task.

  6. #6
    Join Date
    Oct 2002
    Posts
    7

    Thumbs up soln

    #include "stdio.h"
    void main()
    {
    double i= 23.55;
    char temp[10], temp1[10];
    int val1, val2;
    sprintf(temp,"%.2f",i);
    for (int j=0;((temp1[j]=temp[j])!='\0')&&(temp[j]!='.');j++);
    if (temp1[j]=='\0')
    {
    sscanf(temp1,"%d",&val1);
    val2=0;
    }
    else
    {
    temp1[j]='\0';
    sscanf(temp1,"%d",&val1);
    j++;
    for (int k=0;((temp1[k]=temp[j])!='\0');j++,k++);
    sscanf(temp1,"%d",&val2);
    }
    /* val1 contains integer & val2 contains fraction*/
    }

    regards,
    sursura

  7. #7
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    59
    Maybe this would be a bit easier...


    // Value to be "split"
    float value (1.999);

    // Set the decimal precision
    int precision(2);

    int integer= (int) value;
    int fraction = (int) ((value - integer)*pow(10, precision));

    // integer = 1 and fraction = 99

    Villemos.
    Last edited by villemos; October 30th, 2002 at 11:02 AM.

  8. #8
    Join Date
    Oct 2001
    Posts
    745
    Thanks...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured