Thêm dấu phẩy vào đây số javascript

Một giải pháp kỹ lưỡng hơn

Cốt lõi của điều này là replacecuộc gọi. Cho đến nay, tôi không nghĩ bất kỳ giải pháp đề xuất nào xử lý tất cả các trường hợp sau:

  • Số nguyên: 1000 => '1,000'
  • Dây: '1000' => '1,000'
  • Đối với chuỗi:
    • Bảo toàn số không sau số thập phân: 10000.00 => '10,000.00'
    • Loại bỏ các số 0 đứng đầu trước số thập phân: '01000.00 => '1,000.00'
    • Không thêm dấu phẩy sau số thập phân: '1000.00000' => '1,000.00000'
    • Bảo tồn hàng đầu -hoặc +:'-1000.0000' => '-1,000.000'
    • Trả về, không sửa đổi, các chuỗi chứa các chữ số không: '1000k' => '1000k'

Các chức năng sau đây làm tất cả các bên trên.

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

Bạn có thể sử dụng nó trong một plugin jQuery như thế này:

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};

16 hữu ích 1 bình luận chia sẻ