Getting the fractional part of a double value in integers without loss of precision

I want to convert the fractional part of a double value to the nearest 4 digits to an integer. but when I do this, I lose accuracy. Is there a way so that I can get the exact value?

#include<stdio.h> int main() { double number; double fractional_part; int output; number = 1.1234; fractional_part = number-(int)number; fractional_part = fractional_part*10000.0; printf("%lf\n",fractional_part); output = (int)fractional_part; printf("%d\n",output); return 0; } 

I expect the result to be 1234, but it will give 1233. Please suggest a way so that I can get the desired result. I want a solution in C.

+2
source share
4 answers

Assuming you want to return the positive part even for negative values, I would go with

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

which should give the expected result of 1234 .

If you don’t round and just crop the value

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

(which essentially matches your source code), you get an unexpected result of 1233 as 1.1234 - 1.0 = 0.12339999999999995 in double precision.

Without using round() you will 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, be removed again.

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

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

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; } 
+1
source

The solution for any number can 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; } 
+1
source

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; } 
0
source

Source: https://habr.com/ru/post/970181/


All Articles