-4

This is my output now

cost = 12.88;
printf("Cost: %.0lf dollars and %.2lf cents", cost, cost-floor(cost));

//output

12 dollars and 0.88 cents

I need my output to look something like this

cost = 12.88
printf("%d Dollars and %d cents", cost)

output

12 dollars and 88 cents
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    Cents = Dollars * 100? – Adrian Mole Sep 03 '21 at 22:16
  • 1
    Multiply `cost-floor(cost)` by `100`. You should also round it because floating point is approximate. – Barmar Sep 03 '21 at 22:17
  • Does this answer your question? [Extract fractional part of double \*efficiently\* in C](https://stackoverflow.com/questions/5589383/extract-fractional-part-of-double-efficiently-in-c) – Nevus Sep 04 '21 at 08:42

1 Answers1

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

void print_cost(double cost)
{
    double int_part;
    double fract_part = modf(cost, &int_part);
    printf(
        "%d Dollars and %d cents", //"%d" based on your example
        (int) int_part, //we must therefore cast to integer
        abs((int)(fract_part * 100.0)) //fract is signed, abs value needed
    );
}

int main()
{
    print_cost(12.88);
    print_cost(-12.88);
    print_cost(12.8899);
    return 0;
}

Reference:

Erdal Küçük
  • 4,810
  • 1
  • 6
  • 11