Obtaining the Rest of a Floating Point

Asked

Viewed 385 times

3

I have a doubt about that.

Let’s say I have a floating point, with the value 1.13 ( Minutes.Seconds ) How do I get the rest ( 13 ) from the floating point?

Minutes . Seconds ( Rest ) 1 . 13

How do I get 13 from floating point?

4 answers

3

You can make a cast to obtain the integer value of 1.13 that is 1, then just make this equation: partedecimal = valordouble - parteinteira to get the value 0.13, i.e., its decimal part.

See the adaptation:

#include <stdio.h>

double obter_parte_decimal(double);

int main(void)
{
    printf("\nParte decimal de 1.13 = %f", obter_parte_decimal(1.13)); /*O valor que vc deseja obter.*/
    printf("\nParte decimal de 1.23 = %f", obter_parte_decimal(1.23));
    printf("\nParte decimal de 2.19 = %f", obter_parte_decimal(2.19));

    return 0;
}

double obter_parte_decimal(double valor)
{
    return valor - (int)valor;
}

Exit:

Decimal part of 1.13 = 0.130000
Decimal part of 1.23 = 0.230000
Decimal part of 2.19 = 0.190000

I created the function obter_parte_decimal to achieve the goal and return the decimal part, whose signature is double obter_parte_decimal(double); this way you can take a better advantage of it.

Source: https://stackoverflow.com/questions/499939/extract-decimal-part-from-a-floating-point-number-in-c

3

Three forms:

#include <math.h>

double a=1.13;

// -> Forma 1
double f1 = a - ((long) a);

// -> Forma 2
double temp;
double f2 = modf(a, &temp);

// -> Forma 3
double f3 = remainder(a, 1.0);

After executing:

f1 = 0.130000
f2 = 0.130000
f3 = 0.130000

Multiplying the result by 100.0, for example, you get 13.

source: Extract fractional part of double efficiency in C

2

#include <math.h>

double x = 1.13;
double resto = floor((x - floor(x)) * 100);
//                    ^^^^^^^^^^^^ <== 0.13

0

    #include <stdio.h>

/*Programa que separa as partes real e inteira de um valor real.*/

int main()
{
   float num = 4.13;
   float parteDec = 0;
   int   parteInt = 0;

   parteInt = num;
   parteDec = num - parteInt;

   printf("Parte inteira %i\n",parteInt); //Saída = 4
   printf("Parte decimal %g\n",parteDec); //Saída = 0.13
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.