[DAY30] 숫자에 콤마(,) 찍히게하기

1nxeo·2023년 3월 7일

항해99

목록 보기
27/63
post-thumbnail
 // Input
  const [name, setName] = useState("");
  const [num, setNum] = useState(0);
  const changeNum = (e) => {
    const val = e.target.value;
    const removedCommaValue = Number(val.replaceAll(",", ""));
    setNum(removedCommaValue.toLocaleString());
  };
  const savedAlarm = (e) => {
    alert(`name : ${name}, price : ${num}`);
  };

replaceAll(",","") 은 ","을 ""로 대체해준다.

replaceAll(pattern, replacement)

toLocaleString()
:요소가 문자열로 변환되고 이 문자열은 locale 고유 문자열(가령 쉼표 “,”)에 의해 분리됨

arr.toLocaleString([locales[, options]]);

이 때, 입력창에는 ,가 찍히고 알럿창에는 안찍히게 하려면

  // Input
  const [name, setName] = useState("");
  const [num, setNum] = useState(0);

  const changeNum = (e) => {
    const val = e.target.value;
    const removedCommaValue = Number(val.replaceAll(",", ""));
    setNum(removedCommaValue.toLocaleString());
  };
  const savedAlarm = (e) => {
    alert(`name : ${name}, price : ${num.replaceAll(",", "")}`);
    setName("");
    setNum(0);
  };

이렇게 해주면 됨

<h1>Input</h1>
      <Box>
        <label>이름</label>
        <StInput value={name} onChange={(e) => setName(e.target.value)} />
        <label>가격</label>
        <StInput value={num} onChange={changeNum} />
        <Button onClick={savedAlarm}>저장</Button>
      </Box>
      
      
const Box = styled.div`
  display: flex;
  align-items: center;
`;

const StInput = styled.input`
  font-size: 15px;
  width: 200px;
  height: 40px;
  border-radius: 10px;
  border: 1px solid black;
`;
profile
항상 피곤한 인서의 개발블로그

0개의 댓글