添加逗号到输出

时间:2017-12-09 00:00:47

标签: javascript jquery regex

我创建了一个计算器,通过特定计算显示节省的输出。我只需要使用逗号格式化结果并且是货币,因此它不会显示小数点后的每个数字。例如,如果结果是:

$ 2500.566695969 我只想要它显示: $ 2,500.56

我希望这是有道理的,我尝试了几个方法来将逗号放在正确的位置,但没有任何效果。我对jQuery有点新,这是我第一次尝试这样的计算器。任何帮助都非常感谢。以下是我的代码。

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║ 677 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

2 个答案:

答案 0 :(得分:1)

这看起来有点令人讨厌,但下面是一个有效的功能。

它接受包含数字的字符串。字符串是否包含'$'无关紧要。

它返回一个用逗号格式化的字符串,不带前面的'$',但当然很容易添加。

function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
	return str;
    return ret;
}

let elem = document.getElementById('money');
elem.innerHTML = '$' + toCurrency(elem.innerHTML);
<p id="money">$2500.566695969</p>

答案 1 :(得分:0)

您可以在替换功能中尝试import requests from bs4 import BeautifulSoup import urllib2 import shutil import urlparse import os def download(url, fileName=None): def getFileName(url,openUrl): if 'Content-Disposition' in openUrl.info(): # If the response has Content-Disposition, try to get filename from it cd = dict(map( lambda x: x.strip().split('=') if '=' in x else (x.strip(),''), openUrl.info()['Content-Disposition'].split(';'))) if 'filename' in cd: filename = cd['filename'].strip("\"'") if filename: return filename # if no filename was found above, parse it out of the final URL. return os.path.basename(urlparse.urlsplit(openUrl.url)[2]) r = urllib2.urlopen(urllib2.Request(url)) try: fileName = fileName or getFileName(url,r) with open(fileName, 'wb') as f: shutil.copyfileobj(r,f) finally: r.close() URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011' src = requests.get(URL) soup = BeautifulSoup(src.content, 'html.parser') node_list = [ t.find('a')['class'][0] for t in soup.findAll("div", { "class" : "excel" }) ] url_list = [] for url in node_list: node = requests.get("https://data.gov.in/node/{0}/download".format(url)) soup = BeautifulSoup(node.content, 'html.parser') content = soup.find_all("meta")[1]["content"].split("=")[1] url_list.append(content) print("download : " + content) download(content) 而不是当前的正则表达式。