How to get the exact fractional part from a floating point number as an integer?

There are many questions and answers about decimal and integer extraction from floating point numbers and getting output for some specific decimal points. But no one could solve my problem. Please, if someone can help me solve my problem-

I actually tried to extract the exact fractional part from the floating point number. I tried with this:

float f=254.73;

int integer = (int)f;
float fractional = f-integer;

printf ("The fractional part is: %f", fractional);

But conclusion: 0.729996. For this reason, when I did this:

float f=254.73;

int integer = (int)f;
float fractional = f-integer;
int fractional_part_in_integer = ((int)(f*100)%100);

printf ("The value is: %d", fractional_part_in_integer);

72 . 73 254.73. , %.2f printf() . . , 73. , , 254,73, 73 , ?

, .

+6
3

- ceil <math.h>.
float 254.73 254.7299957275390625000000.
f-integer 0.7299957275390625000000.
100 ceil 72.99957275390625000000.

int fractional_part_in_integer = ((int)ceil(fractional*100)) % 100;

: @Sneftel, .

, round math.h f

float f=254.73;

int int_part = (int)f;
float fractional = round(f*100)/100 - int_part;
int fractional_part_in_integer = (int)(fractional*100);

printf("%d, %d\n ", int_part, fractional_part_in_integer);

:

254, 73
+1

?

.

modf() modff()

double modf(double value, double *iptr);
float modff(float value, float *iptr);

modf ,...
C11 §7.12.6.12 2

#include <math.h>

double value = 1.234;
double ipart;
double frac = modf(value, &ipart);

, .

double value = 254.73;
value = round(value*100.0);

double frac = fmod(value, 100);  // fmod computes the floating-point remainder of x/y.
double ipart = (value - frac)/100.0;

printf("%f %f\n", ipart, frac);
254.000000 73.000000

: OP 254.73, float 254.729995727539...

float f = 254.73;
printf("%.30f\n", f);
// 254.729995727539062500000000000000
+10

sprintf sscanf, , . %*d . , .

#include <stdio.h>        

int main( void)           
{                         
    char fp[30];          
    int fraction;         
    float f = 254.73f;    

    sprintf ( fp, "%.2f", f);
    sscanf ( fp, "%*d.%d", &fraction);
    printf ( "%d\n", fraction);

    return 0;                  
}
+2

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


All Articles