[React][utility] 세자리 마다 콤마 추가 문자열 리턴

김민재·2023년 7월 28일

세자리 마다 Comma 찍어서 리턴하기

  • 숫자 일때, 문자열로 변경하여 리턴
  • 세자리 마다 , 찍기
/**
* 매 세자리 마다 콤마를 추가한 문자열 리턴
* @param nun number
*/
export const commafy = (num : number) : string => {
  const str : string[] = num.toString().split('.');
  if (str[0].length >=4) {
    str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
  }
  return str.join(',');
};

사용 방법

import React from 'react'
import { commafy } from 'src/utils/utility';

function CommafyTest () : React.ReactElement {
	const num1 = 1000000;
	const num2 = 5000000000;
	const num3 = 100;
  
return (
  <div>
  	<p>{commafy(num1)}</p> //1,000,000
    <p>{commafy(num2)}</p> //5,000,000,000
	<p>{commafy(num3)}</p> //100
  </div>
 );
}

export default CommafyTest;
profile
주니어 개발자 (Front-End)

1개의 댓글

comment-user-thumbnail
2023년 7월 28일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기