Getting the fractional part of a double value in integer without losing precision

点点圈 提交于 2019-12-05 20:30:00

Assuming you want to get back a positive fraction even for negative values, I'd go with

(int)round(fabs(value - trunc(value)) * 1e4)

which should give you the expected result 1234.

If you do not round and just truncate the value

(int)(fabs(value - trunc(value)) * 1e4)

(which is essentially the same as your original code), you'll end up with the unexpected result 1233 as 1.1234 - 1.0 = 0.12339999999999995 in double precision.

Without using round(), you'll also get the expected result if you change the order of operations to

(int)(fabs(value * 1e4 - trunc(value) * 1e4))

If the integral part of value is large enough, floating-point inaccuracies will of course kick in again.

You can also use modf() instead of trunc() as David suggests, which is probably the best approach as far as floating point accuracy goes:

double dummy;
(int)round(fabs(modf(value, &dummy)) * 1e4)

number= 1.1234, whole=1, fraction=1234

int main()
{
 double number;
 int whole, fraction;
 number = 1.1234;
 whole= (int)number;
 fraction =(int)(number*10000);
 fraction = fraction-(whole *10000);
 printf("%d\n",fraction);
 printf("%d\n",whole);
 return 0;
}

A solution for any number could be:

#include <cmath>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{ 
float number = 123.46244;
float number_final;
float temp = number;  // keep the number in a temporary variable
int temp2 = 1;        // keep the length of the fractional part

while (fmod(temp, 10) !=0)   // find the length of the fractional part
{
    temp = temp*10;
    temp2 *= 10;
}

temp /= 10;       // in tins step our number is lile this xxxx0
temp2 /= 10;
number_final = fmod(temp, temp2);

cout<<number_final;

getch();
return 0;
}

Use modf and ceil

#include <stdio.h>
#include <math.h>

int main(void)
{
    double param, fractpart, intpart;
    int output;

    param = 1.1234;
    fractpart = modf(param , &intpart);
    output = (int)(ceil(fractpart * 10000));
    printf("%d\n", output);

    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!