Tôi muốn xóa dấu phẩy khỏi chuỗi và tính toán số tiền đó bằng JavaScript.
Ví dụ, tôi có hai giá trị đó:
- 100.000.00
- 500.000,00
Bây giờ tôi muốn xóa dấu phẩy khỏi chuỗi đó và muốn tổng số tiền đó.
Tôi muốn xóa dấu phẩy khỏi chuỗi và tính toán số tiền đó bằng JavaScript.
Ví dụ, tôi có hai giá trị đó:
Bây giờ tôi muốn xóa dấu phẩy khỏi chuỗi đó và muốn tổng số tiền đó.
Câu trả lời:
Để xóa dấu phẩy, bạn cần sử dụng replacetrên chuỗi. Để chuyển đổi thành float để bạn có thể thực hiện các phép toán, bạn sẽ cần parseFloat:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
Câu trả lời liên quan, nhưng nếu bạn muốn chạy dọn dẹp một người dùng nhập các giá trị vào biểu mẫu, đây là những gì bạn có thể làm:
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
Sử dụng ngày quốc tế địa phương qua format. Thao tác này sẽ xóa bất kỳ đầu vào xấu nào, nếu có, nó sẽ trả về một chuỗi NaNmà bạn có thể kiểm tra. Hiện tại, không có cách nào để xóa dấu phẩy như một phần của ngôn ngữ (kể từ ngày 10/12/19) , vì vậy bạn có thể sử dụng lệnh regex để xóa dấu phẩy bằng cách sử dụng replace.
ParseFloat chuyển đổi định nghĩa kiểu này từ chuỗi thành số
Nếu bạn sử dụng React, đây là hàm tính toán của bạn có thể trông như thế nào:
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
}
replacevàparseFloat. đây là trường hợp thử nghiệm nhanh: jsfiddle.net/TtYpH