round up a real number upto two decimal values

Discussion in 'C' started by saiganesh, Dec 10, 2015.

  1. saiganesh

    saiganesh New Member

    Joined:
    Dec 8, 2015
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    tell me round off a real number in 2nd decimal place: input-> output; 7.632342534245 -> 7.60; 8.85 -> 8.90; 3.96 -> 4.00

    i wrote below code which is working but my problem is if it more than two decimal value i have to change every time the 10 to 100. so tell me how can i solve this problem.
    Code:
    #include <stdio.h>
    
    int main() 
    {
     //int *precison=3;
       
       float bill_amount,m,a,d;
       
       printf("enter the bill amount ");
       
       scanf("%f",&bill_amount);
       
       printf("entered bill amount:%f\n",bill_amount);
       
       m=bill_amount*10;
       
       a=m+0.5;
       
       d=a/10;
       
       printf("m=%.2f\n",m);
       
       printf("a=%.2f\n",a);
       
       printf("d=%.2f\n",d);
     
    }
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    >>my problem is if it more than two decimal value i have to change every time the 10 to 100

    Why is that a problem?

    However you do it, you're going to have to work out how much to remove from the number, if it's 7.632342534 to 1dp then 0.032342534, if 2dp then 0.002342534, etc. And the easiest way to do that is to multiply it by 10, 100 etc, remove everything right of the dot then divide it again, which is what you're doing.

    If the problem is that you don't know how many dp until runtime, then extend the code to calculate the factor by which the number must be multiplied or divided, i.e. if they say 2 dp, then 10*10, if 3 then 10*10*10, etc - I'm sure you can work out how to do that in a for loop.
     
  3. mikey1989

    mikey1989 New Member

    Joined:
    Jan 9, 2016
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    your can use like this:
    HTML:
    float a=123.567f;
    printf("%.2f",a);
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice