Tell me, I can not understand. There is a code

#include <stdio.h> int main(void) { float money; do { printf ("How much change should I give you?\n"); money = GetFloat(); } while (money<0); printf("%.2f\n", money); } 

How can I extract decimal places from the variable float?

  • what does it mean to extract? Do you want to get only the fractional part? - Mikhail Vaysman
  • yes, only fractional - Myroslav Ivaskevich

1 answer 1

Use the modf function. It should be borne in mind that the sign of the fractional part will be the same as the sign of the original number. For negative numbers, the fractional part will be negative.

 float money; double fractpart, intpart; money = 8.12; fractpart = modf(money, &intpart); printf("Integral part = %lf\n", intpart); printf("Fraction Part = %lf \n", fractpart); 
  • for negative it may work a little unexpectedly. And money - (int)money is somehow more familiar ... - pavel
  • what do you mean by unexpected? - Mikhail Vaysman
  • negative fractional part for example. How many people familiar with mathematics assume that the fractional part is strictly less than 1 and greater than or equal to 0. - pavel
  • added this in response. - Mikhail Vaysman
  • thanks everyone !!!! - Myroslav Ivaskevich