如何在Javascript / Python / Django中添加千分隔符到数字



我想问一下,当我输入数字和输出时,如何在数字中添加千位分隔符。

例如,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

爪哇语

$('.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);
});

Models.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:,}'

它也适用于浮子型淡水河谷。这有点复杂,但我真的很喜欢分享我的想法。它基于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('.')

最新更新