컴퓨터 엑셀 워드 포토샵 구글어스 WINDOWS JAVASCRIPT JAVA C++

 
Saturday, February 24, 2007

C언어] 숫자 천 단위, 3자리마다 쉼표(콤마) 넣기; 1000 Number Comma


다른 언어들에는 숫자 천단위마다 쉼표를 넣는 방법이 제공되거나, 또는 정규식으로 쉽게 구현할 수 있지만, C에서는 좀 힘듭니다.

쉼표 넣기 C소스는 많이 있는데, 마이너스 부호(-)를 처리하지 못하거나, 즉 음수에 콤마를 넣을 수 없거나, 소수점 이하 부분을 처리하지 못하는 등의 문제가 있었습니다. 어제 뉴스그룹에서 좋은 소스를 발견했습니다. 다음의 commify() 라는 함수입니다.

다만, 정수에 쉼표를 넣을 때는, 끝에 마침표가 찍히는 문제가 있어서, 그 마침표를 제거하는 코드를 메인 함수에 추가했습니다.

commify 함수의 3번째 인수인 "int round" 는, 소수점 몇째 자리까지 나타낼지를 지정하는 것입니다.

숫자 세자리(1000단위)마다 콤마 찍기 예제


소스 파일명: example.cpp
※ 아래 박스 클릭 후, 키보드 화살표 키로 좌우 스크롤 가능함
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *commify(double val, char *buf, int round);


int main (void) {
  char buf[50];

  // 실수(float)에 콤마 넣기
  printf("%s\n", commify(-1234567890.55, buf, 2));
  // 출력 결과: -1,234,567,890.55


  // 정수(int)에 콤마 넣기
  printf("%s\n", commify(-1234567890, buf, 0));
  // 출력 결과: -1,234,567,890.


  // 정수(float)에 콤마 넣기 + 마침표 제거
  commify(-1234567890, buf, 0);
  buf[strlen(buf) - 1] = '\0';
  printf("%s\n", buf);
  // 출력 결과: -1,234,567,890


  return 0;
}




// http://groups.google.co.kr/group/comp.lang.c/msg/165f11c5f832321e?dmode=source

/*****************************************************************************
 *                                commify()                                  *
 *                                                                           *
 *  Commify a number, that is add commas between every third digit ahead of  *
 *  the decimal point.  Rounds off to abs(round) digits following the        *
 *  decimal point. Stores the results into the buf[] passed to the function  *
 *  and returns a pointer to it.  Uses the standard library function fcvt()  *
 *  to do the conversion from the double val to the string of digits.        *
 *                                                                           *
 *****************************************************************************/
char *commify(double val, char *buf, int round) {
  static char *result;
  char *nmr;
  int dp, sign;


  result = buf;

  if (round < 0)                        /*  Be sure round-off is positive  */
    round = -round;

  nmr = fcvt(val, round, &dp, &sign);   /*  Convert number to a string     */

  if (sign)                             /*  Prefix minus sign if negative  */
    *buf++ = '-';

  if (dp <= 0){                         /*  Check if number is less than 1 */
    if (dp < -round)                    /*  Set dp to max(dp, -round)      */
      dp = -round;
    *buf++ = '0';                       /*  Prefix with "0."               */
    *buf++ = '.';
    while (dp++)                        /*  Write zeros following decimal  */
      *buf++ = '0';                     /*     point                       */
  }
  else {                                /*  Number is >= 1, commify it     */
    while (dp--){
      *buf++ = *nmr++;
      if (dp % 3 == 0)
        *buf++ = dp ? ',' : '.';
    }
  }

  strcpy(buf, nmr);                     /*  Append rest of digits         */
  return result;                        /*  following dec pt              */
}





tag: cpp
C언어 | C/C++ (Visual C++)

0 Comments:

Post a Comment

<< Home RSS 2.0 feed

구글 Google 에서 제공하는 무료 블로그 서비스인 블로거 Blogger 의 인터넷 주소는 www.blogger.com 입니다. Blogger 에 블로그를 만들면, blogspot.com 이라는 주소에 블로그가 생성됩니다.
블로그를 직접 방문하지 않고도 최신 게시물을 구독하려면 RSS 2.0 feed 주소를 리더기에 등록하시면 됩니다.
Previous Posts
Monthly Archives
Top