C 如何将逗号放入float中?

问题描述 投票:0回答:1

我想把逗号放到float中,就像这样:input: 12345.678输出: $12,345.678

我看到过一个用char[]解决这个问题的方法,但是如果我只想用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;
}

这些都是我做过的代码,当然,并没有按照我想要的方式工作。

对不起,英语和编程技术不好。

c comma
1个回答
0
投票

你看 strfmon.

如果你真的想有自己的代码,可以用这个。

#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
}

如果你会用c++,还有一种方法。

#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
}
© www.soinside.com 2019 - 2024. All rights reserved.