Mega Code Archive

 
Categories / C / Code Snippets
 

Handling monetary values as integers

#include <stdio.h> int main() { float amounts[5]; long dollars[5]; long cents[5]; int j = 0; printf("Enter five monetary values separated by spaces:\n"); for(j = 0 ; j<5 ; j++) scanf("%f", &amounts[j]); for(j = 0 ; j<5 ; j++) { dollars[j] = (long)amounts[j]; cents[j] = (long)(100.0*(amounts[j]-dollars[j])); } printf("\n"); for(j = 0 ; j<5 ; j++) { printf(" $%d.%02d", dollars[j], cents[j]); } printf("\n"); }