Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare float variable to only contain 3 decimal places

Tags:

c

Is this even possible? i tried to google it but i cant seem to find the right answer.

I need to limit the decimal places since the answer will really differ if there is only 3 decimal places than 5, so i was hoping that you could help me with these. i know how to print with 3 decimal places but to declare a variable to only hold 3 decimal places is something i do not know. i could also use some links if you have any.

float sinfa(float num1)
{
    float fc;
    float powers;
    float rad_angle;

    rad_angle = num1 * (PI / 180.0);
    powers = pow(num1,4);
    fc = sin(rad_angle)-powers+1;
    return (fc);
}

float sinfb(float num2)
{
    float fd;
    float powerss;
    float rad_angle1;

    rad_angle1 = num2 * (PI / 180.0);
    powerss = pow(num2,4);
    fd = sin(rad_angle1)-powerss+1;
    return (fd);
}

float tp(float fa,float fb,float num1,float num2)
{
    float p;
    float fm2 = fa*num2;
    float fm1 = fb*num1;
    p = (fm2-fm1)/(fa-fb);
    return (p);
}

float sinp(float p1)
{
    float fop;
    float ppowers;
    float rad_angle2;

    rad_angle2 = p1 * (PI / 180.0);
    ppowers = pow(p1,4);
    fop = sin(rad_angle2)-ppowers+1;
    return (fop);
}

Thank you

like image 950
magicianiam Avatar asked Sep 10 '25 23:09

magicianiam


2 Answers

It can be done!

int intVal = 1.234567 * 1000;          // result: 1234
float floatVal = (float)intVal / 1000; // result: 1.234

The trick is to:

  1. Move the required number of digits to the left-hand side of the decimal place.
  2. Truncate all the digits on the right-hand side of the decimal place.
  3. Move the required number of digits back to the right-hand side of the decimal place.
like image 153
Nocturno Avatar answered Sep 15 '25 04:09

Nocturno


Can't be done. A float is a 32-bit floating-point value in every C compiler I have ever used. There is nothing standard in the language to redefine how it works.

You could write a set of fixed-point functions that store values multiplied by 1000, or use a general library that implements fixed-point with arbitrary precision and set the precision to 3 decimal digits.

C++ fixed point library?

like image 35
steveha Avatar answered Sep 15 '25 05:09

steveha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!