본문 바로가기

# 프로그래밍 개발/03. Web

[React/JS] 숫자 쉼표 찍기, 소수 포함 라이브러리 추천

반응형

요즘 웹 툴을 개발하고 있는데요. 주식 코인 물타기 계산기를 계산하던 와중에, 아무래도 화폐의 숫자이기 때문에 천 단위로 쉼표를 찍어야 할 것 같다라는 생각이 들었습니다. 

생각보다 쉽게 구현할 수 있을 것이라 생각했었는데요. 제가 정규식 표현에는 약해서 빙빙 돌아서, 결국은 라이브러리를 사용하게 되었습니다. 리엑트의 장점이 라이브러리 사용아닐까요? 장점을 최대한 이용해야 겠어요! 

추천하는 라이브러리는 react-number-format 이라는 라이브러리입니다.

 

react-number-format

React component to format number in an input or as a text.. Latest version: 4.9.3, last published: a month ago. Start using react-number-format in your project by running `npm i react-number-format`. There are 820 other projects in the npm registry using r

www.npmjs.com

 

설치 방법

npm install react-number-format --save

해당 라이브러리를 설치하시고, 

InputField 사용하시듯 똑같이 사용하시면 자동으로 쉼표를 찍어줍니다. 

물론, InputField는 아니고 NumberFormat 이라고 해야 합니다. 

 

사용 예시

<NumberFormat
  value={2456981}
  className="foo"
  displayType={'text'}
  thousandSeparator={true}
  prefix={'$'}
  renderText={(value, props) => <div {...props}>{value}</div>}
/>;

옵션 중에 customInput 이라는 것도 있어서, 기존에 사용하고 있던 클래스를 변경하지 않고 해당 클래스를 customInput에 넣으면 현재 사용하고 계신 스타일을 유지한 상태로 쉼표만 찍는 형태로 구현하실 수 있습니다. 

 

아래는 현재 제가 구현하고 있는 물타기 계산기 코드 중 일부입니다. 

<div>
    <NumberFormat
        label="보유 평단"
        customInput={TextField}
        style={{ margin: "5px" }}
        thousandSeparator={true}
        fullWidth
        type="text"
        decimalSeparator="."
        inputRef={investedAvg}
        InputProps={{
            endAdornment: (
                <InputAdornment position="end">
                    <div className="text-primary fw-700">원</div>
                </InputAdornment>
            )
        }}
        onValueChange={
            (values) => {
                const { formattedValue, value } = values;
                // console.log(value);
                setAvg(value);
            }
        }
    />

    <NumberFormat
        label="보유 수량"
        customInput={TextField}
        style={{ margin: "5px" }}
        thousandSeparator={true}
        fullWidth
        type="text"
        decimalSeparator="."
        inputRef={investedNum}
        InputProps={{
            endAdornment: (
                <InputAdornment position="end">
                    <div className="text-primary fw-700">개</div>
                </InputAdornment>
            )
        }}
        onValueChange={
            (values) => {
                const { formattedValue, value } = values;
                setNum(value);
            }
        }
    />

    <NumberFormat
        label="투자 금액 (수정 불가)"
        customInput={TextField}
        style={{ margin: "5px" }}
        thousandSeparator={true}
        fullWidth
        value={myInvestMoney}
        InputProps={{
            endAdornment: (
                <InputAdornment position="end">
                    <div className="text-primary fw-700">원</div>
                </InputAdornment>
            )
        }}
        disabled
    />
</div>

 결과는 아래와 같습니다. 

 

 

웹즈툴 | 웹에서는 모든 것이 가능하다

 

webztool.virtualitsoft.com

 

역시... 리액트나 뷰는 직접 구현하기 보다는 라이브러리가 있는지 없는지 찾아보는게 

일하는 시간을 줄이는 길인 것 같습니다. 오늘 하루종일 정규식 가지고 씨름했는데,, 필요없네요. 

반응형