JavaScript를 사용하여 문자열에서 쉼표 제거


97

문자열에서 쉼표를 제거하고 JavaScript를 사용하여 그 양을 계산하고 싶습니다.

예를 들어 다음 두 가지 값이 있습니다.

  • 100,000.00
  • 500,000.00

이제 해당 문자열에서 쉼표를 제거하고 그 총액을 원합니다.

답변:


172

쉼표를 제거하려면 replace문자열에을 사용해야 합니다. 수학을 할 수 있도록 부동 소수점으로 변환하려면 다음이 필요합니다 parseFloat.

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

3
네, replaceparseFloat. 여기에 빠른 테스트 케이스는 다음과 같습니다 jsfiddle.net/TtYpH
그림자 마법사가 당신을 위해 귀입니다

1
2017 년 입니다 . 로케일 문자열을 오가는 방법이 없습니까? 이 기능을 어떻게 되돌릴 수 있습니까? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/... . 여기에 별도의 질문을 게시 : stackoverflow.com/questions/41905406/...
코스타

4

관련 답변이지만 양식에 값을 입력하는 사용자를 정리하려면 다음을 수행하십시오.

const numFormatter = new Intl.NumberFormat('en-US', {
  style: "decimal",
  maximumFractionDigits: 2
})

// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123

// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24

// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN

// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN

를 통해 현지 국제 날짜를 사용합니다 format. 이것은 잘못된 입력을 정리하고, 만약 있다면 NaN당신이 확인할 수 있는 문자열을 반환합니다 . 현재 로케일의 일부로 쉼표를 제거 할 수있는 방법이 없습니다 (19 년 10 월 12기준) . 정규식 명령을 사용하여 replace.

ParseFloat 이 유형 정의를 문자열에서 숫자로 변환합니다.

React를 사용하는 경우 계산 함수는 다음과 같습니다.

updateCalculationInput = (e) => {
    let value;
    value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
    if(value === 'NaN') return; // locale returns string of NaN if fail
    value = value.replace(/,/g, ""); // remove commas
    value = parseFloat(value); // now parse to float should always be clean input

    // Do the actual math and setState calls here
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.