[英]How to add Thousand Separator to number in Javascript / Python / Django
我想问当我输入数字时如何将千位分隔符添加到数字以及 output 中。
例如,10 000 变为 10,000。
我尝试使用 Django intcomma 但它不起作用。
如果你们能帮助我,真的很感激。 下面是我的代码:
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<div class="form-group">
<form name="add_price" id="add_price">
<div class="table-responsive">
<table class="table table-bordered" id="price">
{{ priceformset.management_form }}
{% for price in priceformset %}
<tr>
<td>{{ product.product_price }}</td>
<td>{{ product.product_quantity }}</td>
<td>{{ product.product_total_price }}</td>
</tr>
{% endfor %}
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body
Javascript
$('.textInput').on('change keyup', function() {
product_total_price=0;
var product_price= Number($('#id_Product-0-price').val());
var product_quantity= Number($('#id_Product-0-quantity').val());
product_total_price= product_price * product_quantity;
$('#id_Product-0-total_price').val(product_total_price);
});
模型.py
class Price (models.Model):
product_price = models.CharField(max_length=512,null=True,blank=True)
product_quantity = models.CharField(max_length=512,null=True,blank=True)
product_total_price= models.CharField(max_length=512,null=True,blank=True)
Forms.py
class PriceForm(forms.ModelForm):
product_price =forms.CharField(required=False,label=('Price'),widget=forms.TextInput(
attrs= {
"class":"textInput form-control",
"placeholder" : "Price"
}))
product_quantity =forms.CharField(required=False,label=('Quantity'),widget=forms.TextInput(
attrs= {
"class":"textInput form-control",
"placeholder" : "Quantity"
}))
product_total_price =forms.CharField(required=False,label=('Total Price'),widget=forms.TextInput(
attrs= {
"class":"textInput form-control",
"placeholder" : "Total Price"
}))
class Meta:
model = Price
fields = ('__all__')
在js中很容易做到:
let number = 1000
number.toLocaleString()
这是在 python 中的操作方法:
def place_value(number):
return ("{:,}".format(number))
print(place_value(1000000))
乐意效劳
javascript:
const n = 100000
const formated = n.toLocaleString()
python(需要 python 3.6+):
n = 1000000
formatted = f'{n:,}'
它也适用于浮点型 vale。 这有点复杂,但我真的很喜欢分享我的想法。 它基于 Javascript。
value.toString().split('.').map((v, i) => i===0?v.split('').map((val, idx, self) => ((idx===0)||((self.length-idx)%3!==0))?val:`,${val}`).join(''):v).join('.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.