0

I want to put commas into float like this: input: 12345.678 output: $12,345.678

I have seen a solution using char[] to solve this problem, but how can I do if I only want to use float?

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

int main(void){
  double num;
  printf("Please enter a float: ");
  scanf("%lf", &num);
  do{
    num/=1000;
  }
  while(num >= 1000);
  printf("$%f",num);

  system("PAUSE");
  return 0;
}

These are the code I have done, and of course, it did not work in the way I want.

Sorry for poor English and programming skill.

1 Answers1

0

Look at strfmon.

If you really want to have your own code, you can use this.

#include <stdio.h>
#include <string.h>

void sprintf_money(char* buf, double num) {
  sprintf(buf, "%ld", (long)(num * 100));
  memmove(&buf[strlen(buf) - 1], &buf[strlen(buf) - 2], 3);
  buf[strlen(buf) - 3] = '.';

  char* p = &buf[strlen(buf) - 3];
  while (p - 3 > buf) {
    p = p - 3;
    memmove(p + 1, p, strlen(p) + 1);
    *p = ',';
  }
}


int main() {
  char buf[100];
  sprintf_money(buf, 1234512345.678);
  puts(buf); // output: 1,234,512,345.67
}

If you can use c++, there is another way:

#include <iostream>
#include <iomanip>

int main()
{
    double mon = 12345.67;

    std::cout.imbue(std::locale("en_US.UTF-8"));
    std::cout << std::put_money(mon * 100) << "\n"; // output: 12,345.67
}
shawn
  • 1