ลบเครื่องหมายจุลภาคออกจากสตริงโดยใช้ JavaScript


97

ฉันต้องการลบเครื่องหมายจุลภาคออกจากสตริงและคำนวณจำนวนเงินเหล่านั้นโดยใช้ JavaScript

ตัวอย่างเช่นฉันมีค่าสองค่านี้:

  • 100,000.00
  • 500,000.00

ตอนนี้ฉันต้องการลบเครื่องหมายจุลภาคออกจากสตริงเหล่านั้นและต้องการยอดรวมของจำนวนนั้น

คำตอบ:


172

หากต้องการลบเครื่องหมายจุลภาคคุณจะต้องใช้replaceกับสตริง ในการแปลงเป็น float เพื่อให้คุณสามารถคำนวณได้คุณจะต้องparseFloat:

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

3
ใช่ต้องรวมreplaceและparseFloat. นี่คือกรณีทดสอบสั้น ๆ : jsfiddle.net/TtYpH
Shadow Wizard is Ear For You

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คุณสามารถตรวจสอบได้ ปัจจุบันไม่มีวิธีลบเครื่องหมายจุลภาคเป็นส่วนหนึ่งของภาษา(ณ วันที่ 10/12/19)ดังนั้นคุณสามารถใช้คำสั่ง regex เพื่อลบเครื่องหมายจุลภาคโดยใช้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.