[sample coding] js 수표기 코드 (ex - 인스타 팔로워수)

SeoYng·2022년 1월 11일
0
post-thumbnail

큰 수를 그대로 출력하기보다 한글 수체계로 바꾸는 등의 작업이 필요할때가 있다.
예를들어 인스타그램은 만명이 넘는 숫자에대해 소수 첫째자리까지 표기한후 '만'을 붙이고 있다.
그리고 보통 4자리수 이상의 수에서 3자리마다 콤마를 찍는 수표기가 일반적이다.

이는 정규식을 이용해 생각보다 간단히 구현될수 있다

👀 예제코드 -

📃 .vue

<template>
    <div>{{ followCntTxt }}</div>
</template>

<script>
import { mapState } from 'vuex';
export default {
     computed: {
          // api에서 받아온 값
          ...mapState('followModule', ['followCnt']),
          // 출력 가공
          followCntTxt() {
              const cnt = this.followCnt || 0;
              return cnt < 10000 ? $_getCommaformatNum(cnt) : this.$_convertCnt(cnt);
          },
      },
      
      methods: {
        // 1234567 -> 1,234,567
        $_getCommaformatNum(num) {
          return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
        }
        // over 10000 count
        $_convertCnt(num) {
          let strNum = String(num / 10000);
          // 소수점
          const commaIdx = strNum.indexOf('.');
          const isComma = commaIdx !== -1;
          // 소수점 존재시 첫쨰자리 까지 슬라이스
          if (isComma) {
            // 첫째자리가 0인경우 -> 소숫점 이하 다 버려야함
            const isCommaZero = strNum.charAt(commaIdx + 1) === '0'; // ex) 1.03
            const sliceIdx = isCommaZero ? commaIdx : commaIdx + 2;
            strNum = strNum.substring(0, sliceIdx);
          }
          return strNum + '만';
        },
      },
}
</script>
profile
Junior Web FE Developer

0개의 댓글